Example usage for org.springframework.security.authentication BadCredentialsException BadCredentialsException

List of usage examples for org.springframework.security.authentication BadCredentialsException BadCredentialsException

Introduction

In this page you can find the example usage for org.springframework.security.authentication BadCredentialsException BadCredentialsException.

Prototype

public BadCredentialsException(String msg) 

Source Link

Document

Constructs a BadCredentialsException with the specified message.

Usage

From source file:com.rln.acme.security.MongoDBAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {

    final String password = (String) authentication.getCredentials();
    if (!StringUtils.isNotBlank(password)) {
        logger.warn("User {}: no password provided", username);
        throw new BadCredentialsException("Please enter password");
    }//  w  w w . ja v a 2  s.c o  m

    final UserAccount user = userService.findByUsername(username);
    if (user == null) {
        logger.warn("Username {}, password {}: username and password not found", username, password);
        throw new BadCredentialsException("Invalid Username/Password");
    }

    final List<GrantedAuthority> auths;
    if (CollectionUtils.isNotEmpty(user.getRoles())) {
        auths = AuthorityUtils.commaSeparatedStringToAuthorityList(
                user.getRoles().stream().map(r -> r.getId()).collect(Collectors.joining(",")));
    } else {
        auths = AuthorityUtils.NO_AUTHORITIES;
    }

    return new User(username, password, user.getEnabled(), // enabled
            true, // account not expired
            true, // credentials not expired
            true, // account not locked
            auths);
}

From source file:com.alliander.osgp.shared.security.KeycloakAuthenticationManager.java

@Override
public Authentication authenticate(final Authentication authentication) {
    if (authentication == null) {
        LOGGER.debug(NULL_AUTHENTICATION);
        throw new BadCredentialsException(NULL_AUTHENTICATION);
    }//from  w  w  w . java  2  s.  com

    final String username = authentication.getName();

    final LoginRequest loginRequest = new LoginRequest(username, null, this.application);
    LoginResponse loginResponse = null;

    try {
        loginResponse = this.authenticationClient.loginMellon(loginRequest, this.mellonSharedSecret);
    } catch (final Exception e) {
        LOGGER.debug(LOGIN_ATTEMPT_FAILED, e);
        throw new BadCredentialsException(LOGIN_ATTEMPT_FAILED, e);
    }

    if (loginResponse == null) {
        LOGGER.debug(LOGIN_RESPONSE_IS_NULL);
        throw new BadCredentialsException(LOGIN_RESPONSE_IS_NULL);
    }

    if (!loginResponse.getFeedbackMessage().equals(OK)) {
        LOGGER.debug(LOGIN_RESPONSE_IS_NOT_OK);
        throw new BadCredentialsException(LOGIN_RESPONSE_IS_NOT_OK);
    }

    return this.createCustomAuthenticationInstance(username, loginResponse);
}

From source file:org.osiam.auth.login.internal.InternalAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) {
    Preconditions.checkArgument(authentication instanceof InternalAuthentication,
            "InternalAuthenticationProvider only supports InternalAuthentication.");

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (Strings.isNullOrEmpty(username)) {
        throw new BadCredentialsException("InternalAuthenticationProvider: Empty Username");
    }//  www  . ja v  a  2 s  .com

    if (Strings.isNullOrEmpty(password)) {
        throw new BadCredentialsException("InternalAuthenticationProvider: Empty Password");
    }

    // Determine username
    User user = resourceServerConnector.getUserByUsername(username);

    if (user == null) {
        throw new BadCredentialsException("The user with the username '" + username + "' not exists!");
    }

    String hashedPassword = passwordEncoder.encodePassword(password, user.getId());

    if (resourceServerConnector.searchUserByUserNameAndPassword(username, hashedPassword) == null) {
        throw new BadCredentialsException("Bad credentials");
    }

    User authUser = new User.Builder(username).setId(user.getId()).build();

    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

    for (Role role : user.getRoles()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getValue()));
    }

    return new InternalAuthentication(authUser, password, grantedAuthorities);
}

From source file:com.mycompany.login.filter.AutenticacaoFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
    String login = request.getParameter("j_login");
    String senha = request.getParameter("j_senha");

    try {//from www . ja  va2s . c om
        Usuario usuario = buscarUsuario(login, senha);
        if (usuario != null) {
            Collection<GrantedAuthority> regras = new ArrayList<GrantedAuthority>();
            regras.add(new SimpleGrantedAuthority(usuario.getPermissao()));

            request.getSession().setAttribute("usuarioLogado", usuario);
            mensagem = "Bem vindo: " + usuario.getNomeusuario();
            return new UsernamePasswordAuthenticationToken(usuario.getLogin(), usuario.getSenha(), regras);

        } else {
            mensagem = "Dados Incorretos";
            throw new BadCredentialsException(mensagem);
        }

    } catch (Exception e) {
        throw new BadCredentialsException(e.getMessage());
    }
}

From source file:no.smint.anthropos.authentication.TokenAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Token token = (Token) authentication;
    LdapUserPwd ldapUserPwd = token.getLdapUserPwd();

    if (validateLogin(ldapUserPwd)) {
        Person loggedInUser = getLoggedInUser(ldapUserPwd.getUsername());
        AuthUserDetails authUserDetails = new AuthUserDetails(loggedInUser);

        // Return an updated token with the right user details
        return new Token(ldapUserPwd, authUserDetails);

    }/*from  w w w.  j a  v  a 2s  .co m*/
    throw new BadCredentialsException("Invalid username or password");
}

From source file:gr.abiss.calipso.userDetails.util.SecurityUtil.java

public static void login(HttpServletRequest request, HttpServletResponse response,
        ICalipsoUserDetails userDetails, UserDetailsConfig userDetailsConfig,
        UserDetailsService userDetailsService) {
    if (LOGGER.isDebugEnabled()) {
        if (userDetails != null) {
            LOGGER.debug(request.getMethod() + " login, userDetails email: " + userDetails.getEmail() + ", un: "
                    + userDetails.getUsername() + ", non-blank pw: "
                    + StringUtils.isNotBlank(userDetails.getPassword()));
        }/*  w w w  . ja v a  2  s  .  co  m*/
    }
    if (userDetails != null && StringUtils.isNotBlank(userDetails.getUsername())
            && StringUtils.isNotBlank(userDetails.getPassword())) {
        String token = new String(
                Base64.encode((userDetails.getUsername() + ":" + userDetails.getPassword()).getBytes()));
        addCookie(request, response, userDetailsConfig.getCookiesBasicAuthTokenName(), token, false,
                userDetailsConfig);
        userDetailsService.updateLastLogin(userDetails);
    } else {
        LOGGER.warn("Login failed, force logout to clean any stale cookies");
        SecurityUtil.logout(request, response, userDetailsConfig);
        throw new BadCredentialsException("The provided user details are incomplete");
    }

}

From source file:eu.trentorise.smartcampus.aac.conf.OAuthAuthenticationProvider.java

/**
 * Check that the token is not empty, validate against the {@link TokenStore} if specified,
 * and if it is valid for the given scope (if specified)
 *//*from  ww w .  j a v a  2 s  .co m*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String token = (String) authentication.getPrincipal();
    if (token == null || token.trim().isEmpty()) {
        throw new BadCredentialsException("Authentication token is absent");
    }
    if (tokenStore != null && !tokenStore.validateToken(token)) {
        throw new BadCredentialsException("Authentication token is not valid");
    }
    try {
        if (scope != null && aacURL != null
                && !new AACService(aacURL, null, null).isTokenApplicable(token, scope)) {
            throw new BadCredentialsException("Authentication token is not valid for the required scope");
        }
    } catch (AACException e) {
        throw new BadCredentialsException("Failed to valdiate token scope: " + e.getMessage());
    }
    authentication.setAuthenticated(true);
    return authentication;
}

From source file:ar.com.zauber.commons.social.twitter.security.TwitterAuthenticationProcessingFilter.java

/**
 * @see AbstractAuthenticationProcessingFilter
 *      #attemptAuthentication(HttpServletRequest,
 *      HttpServletResponse)/*w  w  w  . j a  v  a2  s  .c o m*/
 */
@Override
public final Authentication attemptAuthentication(final HttpServletRequest request,
        final HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    if (!request.getMethod().equals("GET")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }

    final String oauthToken = request.getParameter("oauth_token");
    final String oauthVerifier = request.getParameter("oauth_verifier");
    // verifier may be null
    final String denyToken = request.getParameter("denied");

    if (denyToken != null) {
        throw new BadCredentialsException("twitter access denied");
    }

    if (oauthToken == null) {
        throw new AuthenticationServiceException("missing oauth_token parameter");
    }

    return this.getAuthenticationManager()
            .authenticate(new TwitterAuthenticationToken(oauthToken, oauthVerifier));
}

From source file:com.sun.identity.provider.springsecurity.OpenSSOProcessingFilter.java

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {

    SSOToken token = obtainSSOToken(request);
    String username = obtainUsername(token);
    if (debug.messageEnabled())
        debug.message("username: " + (username == null ? "is null" : username));

    if (username == null) {
        throw new BadCredentialsException("User not logged in via Portal! SSO user cannot be validated!");
    }/*from  w  ww .  j  a  v a 2 s .c om*/

    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, token);

    // Place the last username attempted into HttpSession for views
    request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, username);

    setDetails(request, authRequest);

    return this.getAuthenticationManager().authenticate(authRequest);
}

From source file:in.mycp.service.MycpAuthService.java

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    String password = (String) authentication.getCredentials();
    if (StringUtils.isBlank(password)) {
        throw new BadCredentialsException("Please enter password");
    }/*from   ww  w.  j  ava2 s  .c om*/
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    in.mycp.domain.User mycpUser = null;
    try {
        ShaPasswordEncoder passEncoder = new ShaPasswordEncoder(256);
        String encodedPass = passEncoder.encodePassword(password, username);
        mycpUser = in.mycp.domain.User
                .findUsersByEmailEqualsAndPasswordEqualsAndActiveNot(username, encodedPass, false)
                .getSingleResult();
        mycpUser.setLoggedInDate(new Date());
        mycpUser = mycpUser.merge();
        List<Role> roles = Role.findRolesByIntvalLessThan(mycpUser.getRole().getIntval() + 1).getResultList();
        //everybody gets role_user
        //authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
        for (Iterator iterator = roles.iterator(); iterator.hasNext();) {
            Role role = (Role) iterator.next();
            authorities.add(new GrantedAuthorityImpl(role.getName()));
        }

    } catch (EmptyResultDataAccessException e) {
        log.error(e.getMessage());//e.printStackTrace();
        throw new BadCredentialsException("Invalid username or password");
    } catch (EntityNotFoundException e) {
        log.error(e.getMessage());//e.printStackTrace();
        throw new BadCredentialsException("Invalid user");
    } catch (NonUniqueResultException e) {
        throw new BadCredentialsException("Non-unique user, contact administrator");
    } catch (Exception e) {
        throw new BadCredentialsException("Invalid username or password");
    }

    return new User(mycpUser.getEmail(), mycpUser.getPassword(), mycpUser.getActive(), // enabled
            true, // account not expired
            true, // credentials not expired
            true, // account not locked
            authorities);
}