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, Throwable t) 

Source Link

Document

Constructs a BadCredentialsException with the specified message and root cause.

Usage

From source file:es.sas.lopd.infraestructura.seguridad.impl.DaoAuthenticationProvider.java

@SuppressWarnings("deprecation")
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    Object salt = null;// w  w w  .ja va2  s . co  m

    if (this.saltSource != null) {
        salt = this.saltSource.getSalt(userDetails);
    }

    if (authentication.getCredentials() == null) {
        logger.debug("Authentication failed: no credentials provided");

        throw new BadCredentialsException(messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails);
    }

    String presentedPassword = authentication.getCredentials().toString();

    if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
        logger.debug("Authentication failed: password does not match stored value");

        throw new BadCredentialsException(messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails);
    }
}

From source file:org.mitre.openid.connect.assertion.JWTBearerClientAssertionTokenEndpointFilter.java

@Override
public void afterPropertiesSet() {
    super.afterPropertiesSet();
    setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
        @Override/* w  w w. j a  v a  2s . c  o m*/
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException exception) throws IOException, ServletException {
            if (exception instanceof BadCredentialsException) {
                exception = new BadCredentialsException(exception.getMessage(),
                        new BadClientCredentialsException());
            }
            authenticationEntryPoint.commence(request, response, exception);
        }
    });
    setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            // no-op - just allow filter chain to continue to token endpoint
        }
    });
}

From source file:ph.fingra.statisticsweb.security.FingraphAnthenticationProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    Object salt = null;//from  w  w  w.j  av a 2s.  c  o  m

    if (this.saltSource != null) {
        salt = this.saltSource.getSalt(userDetails);
    }

    if (authentication.getCredentials() == null) {
        logger.debug("Authentication failed: no credentials provided");

        throw new BadCredentialsException(
                messages.getMessage("Invalid user id or password. Please try again.", "Bad credentials"),
                userDetails);
    }

    String presentedPassword = authentication.getCredentials().toString();
    logger.debug("userDetails {}, presentedPassword {}", userDetails, presentedPassword);
    if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
        logger.debug("Authentication failed: password does not match stored value");

        //throw new BadCredentialsException(
        //        messages.getMessage("Invalid user id or password. Please try again.", "Bad credentials"),
        //        userDetails);
        throw new PasswordMissmatchUserException("Invalid user id or password. Please try again.", userDetails);
    }

    FingraphUser member = (FingraphUser) userDetails;
    if (MemberStatus.valueOf(member.getStatus()) != MemberStatus.ACTIVE) {
        logger.debug("Authentication failed: un-active user");
        throw new UnverifiedUserException("AbstractUserDetailsAuthenticationProvider.disabled", userDetails);
    }
    if (MemberJoinstatus.valueOf(member.getJoinstatus()) != MemberJoinstatus.APPROVAL) {
        logger.debug("Authentication failed: un-approval user");
        throw new UnapprovalUserException("AbstractUserDetailsAuthenticationProvider.disabled", userDetails);
    }
}

From source file:org.keycloak.adapters.springsecurity.authentication.DirectAccessGrantAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = resolveUsername(authentication.getPrincipal());
    String password = (String) authentication.getCredentials();
    RefreshableKeycloakSecurityContext context;
    KeycloakAuthenticationToken token;// w w w.j  a v  a 2s  .c  o  m
    Collection<? extends GrantedAuthority> authorities;

    try {
        context = directAccessGrantService.login(username, password);
        authorities = KeycloakSpringAdapterUtils.createGrantedAuthorities(context, grantedAuthoritiesMapper);
        token = new KeycloakAuthenticationToken(
                KeycloakSpringAdapterUtils.createAccount(keycloakDeployment, context), authorities);
    } catch (VerificationException e) {
        throw new BadCredentialsException("Unable to validate token", e);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Error authenticating with Keycloak server", e);
    }

    return token;
}

From source file:org.osiam.security.helper.FBClientCredentialsTokenEndpointFilter.java

@Override
/**/*from   ww w .j ava2s  . c om*/
 * Sets the handler, failed -> BadCredentialsException, success -> just continue.
 */
public void afterPropertiesSet() {
    super.afterPropertiesSet();
    setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException exception) throws IOException, ServletException {
            if (exception instanceof BadCredentialsException) {
                exception = // NOSONAR
                        new BadCredentialsException(exception.getMessage(),
                                new BadClientCredentialsException());
            }
            authenticationEntryPoint.commence(request, response, exception);
        }
    });
    setAuthenticationSuccessHandler(new MyAuthenticationSuccessHandler());
}

From source file:org.jutge.joc.porra.security.MongoDBAuthenticationProvider.java

@Override
public UserDetails retrieveUser(final String name, final UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    this.logger.info("MongoDBAuthenticationProvider.retrieveUser");
    boolean valid = true;
    // Make sure an actual password was entered
    final String password = (String) authentication.getCredentials();
    if (!StringUtils.hasText(password)) {
        this.logger.warn("Username {}: no password provided", name);
        valid = false;//  w w w .ja v a 2 s . co  m
    }
    // Look for user and check their account is activated
    final Account account = this.accountService.getByName(name);
    if (account == null) {
        this.logger.warn("Username {}: user not found", name);
        valid = false;
    } else {
        if (!AccountStatus.STATUS_APPROVED.name().equals(account.getStatus())) {
            this.logger.warn("Username {}: not approved", name);
            valid = false;
        }
        // Check password
        final String hashedPassword = BCrypt.hashpw(password, account.getSalt());
        if (!hashedPassword.equals(account.getHashedPass())) {
            this.logger.warn("Username {}: bad password entered", name);
            valid = false;
        }
    }
    if (!valid) {
        final Locale locale = LocaleContextHolder.getLocale();
        final String message = this.messageSource.getMessage("exception.wrongAccountNameAndPass", null, locale);
        final MessageBox messageBox = new MessageBox("wrongAccountNameAndPass", message,
                new ArrayList<String>());
        final List<MessageBox> errorMessages = new ArrayList<MessageBox>();
        errorMessages.add(messageBox);
        final LoginException loginException = new LoginException(errorMessages, name);
        throw new BadCredentialsException("Invalid Username/Password", loginException);
    }

    // Create Springframework-typed User instance
    final List<String> roles = account.getRoles();
    final List<GrantedAuthority> auths = !roles.isEmpty()
            ? AuthorityUtils.commaSeparatedStringToAuthorityList(account.getRolesCSV())
            : AuthorityUtils.NO_AUTHORITIES;
    // enabled, account not expired, credentials not expired, account not locked
    return new User(name, password, true, true, true, true, auths);
}

From source file:org.openmrs.cwf.security.base.BaseAuthenticationProvider.java

/**
 * Maps known exceptions to Spring authentication exceptions.
 * //from   w  w w.j a  va  2  s . com
 * @param e Original exception
 * @return Mapped authentication exception
 */
protected AuthenticationException mapException(ContextAuthenticationException e) {
    // Spring Security does not print the stack trace
    log.trace("Mapping authentication-related exception: " + e.getMessage(), e);
    return new BadCredentialsException(Labels.getLabel(Constants.LBL_LOGIN_ERROR_INVALID), e);
    /*
    if (e instanceof AuthenticationException) {
    return (AuthenticationException) e;
    } else if (e instanceof UserLoginPasswordExpiredException) {
    return new CredentialsExpiredException(Labels.getLabel(Constants.LBL_LOGIN_ERROR_EXPIRED_PASSWORD), e);
    } else if (e instanceof UserLoginExpiredException) {
    return new CredentialsExpiredException(Labels.getLabel(Constants.LBL_LOGIN_ERROR_EXPIRED_USER), e);
    } else if (e instanceof UserLoginException) {
    return new BadCredentialsException(Labels.getLabel(Constants.LBL_LOGIN_ERROR_INVALID), e);
    } else {
    //redundant but uncommon case so ensure visibility by logging error
    log.error(Labels.getLabel(Constants.LBL_LOGIN_ERROR_UNEXPECTED) + ": " + e.getMessage(), e);
    return new AuthenticationServiceException(Labels.getLabel(Constants.LBL_LOGIN_ERROR_UNEXPECTED), e);
    } */
}

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

/**
 * The login function. Use an Authentication instance with the principal set
 * to the user name and the credentials set to the password. Authentication
 * will be granted if the user is permitted for an/this application, the
 * user name is registered and the password matches.
 *
 * @param authentication/*www  .j a va  2 s .c o m*/
 *            An Authentication instance containing user name and password.
 *
 * @return An CustomAuthentication instance containing user name, users
 *         organisation identification, platform domains, user role, user
 *         applications and an authentication token.
 */
@Override
public Authentication authenticate(final Authentication authentication) {

    // Check if user has authentication instance.
    this.checkAuthenticationInstance(authentication);

    // Get user name and password.
    final String username = authentication.getName();
    final String password = (String) authentication.getCredentials();

    // Check user name and password.
    this.checkUsernameAndPasswordForEmptiness(username, password);

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

    // Try to login.
    try {

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

    // Check the response.
    this.checkLoginResponse(loginResponse);

    // Create the CustomAuthentication instance.
    return this.createCustomAuthenticationInstance(username, password, loginResponse);
}