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:fr.insalyon.creatis.vip.api.rest.security.apikey.ApikeyAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(ApikeyAuthenticationToken.class, authentication,
            "Only ApikeyAuthenticationToken is supported");

    User vipUser;//from   w  ww  .  ja v a2 s  .c  o  m
    String apikey = authentication.getCredentials().toString();
    try {
        vipUser = userDAO.getUserByApikey(apikey);
    } catch (DAOException e) {
        logger.error("error when getting user by apikey", e);
        logger.error("Doing as if there is an auth error");
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    if (vipUser == null) {
        logger.info("Cant authenticate because apikey not found:" + apikey);
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    logger.info("apikey OK for " + vipUser.getEmail());
    UserDetails springUser;
    try {
        Map<Group, CoreConstants.GROUP_ROLE> groups = configurationBusiness.getUserGroups(vipUser.getEmail());
        vipUser.setGroups(groups);
        springUser = new SpringCompatibleUser(vipUser);
    } catch (BusinessException e) {
        logger.error("error when getting user groups" + vipUser.getEmail(), e);
        logger.error("Doing as if there is an auth error");
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    checkUserInfo(springUser);
    try {
        logger.info("successful logging for " + springUser.getUsername());
        userDAO.resetNFailedAuthentications(springUser.getUsername());
    } catch (DAOException e) {
        logger.error("Error reseting failed auth attemps ", e);
    }
    return new ApikeyAuthenticationToken(springUser, apikey);
}

From source file:com.gs.config.MyAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UserDetails userDetails = this.customJDBCDaoImpl.loadUserByUsername(authentication.getName());
    //Obtengo los intentos de inicio de sesin hechos por un usuario
    int intentos = usuarioConIntentoFallido.getIntentosUsuario(authentication.getName());
    if (intentos < intentosPosibles && !listUsersLockoutIntentFail.findUserBlockout(authentication.getName())) {
        if (userDetails.isEnabled()) {
            if (userDetails != null && shaPasswordEncoder.isPasswordValid(userDetails.getPassword(),
                    authentication.getCredentials().toString(), null)) {
                usuarioConIntentoFallido.removeUsuario(userDetails.getUsername());
                //Verifico si el usuario ya tiene una sesin abierta, si es as la cierro y le creo su nueva instancia
                verifUserInSession(userDetails.getUsername());
                return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            }// ww w . j a va 2 s.  c o m
            throw new BadCredentialsException("Bad credentials");
        } else {
            throw new DisabledException("User disabled");
        }
    } else {
        throw new IntentLimitExceeded("limite de intentos excedidos");
    }
}

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

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    LOG.debug("Arrive dans attemptAuthentication");
    Authentication ret = null;//from w  w  w .  j a va  2 s .  com
    String SAMLResponse = request.getParameter("SAMLResponse");
    String relayState = request.getParameter(RELAYSTATE);
    if (relayState == null) {
        logger.debug("Pas de relayState null");
    } else if (relayState.isEmpty()) {
        logger.debug("Pas de relayState vide");
    } else {
        if (relayStateRepository == null) {
            relayStateRepository = ApplicationContextProvider.getApplicationContext()
                    .getBean(RelayStateRepositoryService.class);
        }

        if (relayStateRepository.existRelayState(relayState)) {
            logger.debug("retour avec relayState=" + relayState);
        } else {
            logger.error("retour avec mauvais relayState=" + relayState);
            throw new BadCredentialsException("bad csrf relayState");
        }
    }
    EIDASAuthnResponse authnResponse = null;
    IPersonalAttributeList personalAttributeList = null;
    logger.debug("Arrive dans filtre SAML attemptAuthentication");
    //spUrl = configs.getProperty(Constants.SP_URL);

    //Decodes SAML Response
    byte[] decSamlToken = EIDASUtil.decodeSAMLToken(SAMLResponse);

    //Get SAMLEngine instance

    try {
        EIDASSAMLEngine engine = SPUtil.createSAMLEngine(Constants.SP_CONF);
        //validate SAML Token
        authnResponse = engine.validateEIDASAuthnResponse(decSamlToken, request.getRemoteHost(), 0);

    } catch (EIDASSAMLEngineException e) {
        logger.error(e.getMessage());
        if (StringUtils.isEmpty(e.getErrorDetail())) {
            throw new IOException(SAML_VALIDATION_ERROR, e);
        } else {
            throw new IOException(SAML_VALIDATION_ERROR, e);
        }
    }

    Set<GrantedAuthority> authorities = new HashSet<>();
    String userId = null;
    if (authnResponse.isFail()) {
        throw new IOException("Saml Response is fail" + authnResponse.getMessage());
    } else {
        LOG.info("token saml valide cherche userId");
        personalAttributeList = authnResponse.getPersonalAttributeList();

        for (PersonalAttribute pa : personalAttributeList) {
            if (pa.getName().equalsIgnoreCase("personidentifier")) {
                userId = pa.getValue().get(0);
                break;
            }
        }
    }
    if (userId == null) {
        throw new IOException("Pas trouve personidentifier dans attributs SAML");
    }
    //ajoute les attributs de l'utilisateur
    for (String nom : lesNoms()) {
        for (PersonalAttribute pa : personalAttributeList) {
            if (pa.getName().equalsIgnoreCase(nom)) {
                authorities.add(new SimpleGrantedAuthority(pa.getValue().get(0)));
                break;
            }
        }
    }
    //attention c'est un raccourci normalement il faut passer par authentProvider !!!
    authorities.add(ROLE_CLIENT);
    authorities.add(ROLE_USER);
    authorities.add(ROLE_ADMIN);
    authorities.add(ROLE_ANONYMOUS);
    SAML2AssertionAuthenticationToken authTok = new SAML2AssertionAuthenticationToken(userId, authorities);
    authTok.setDetails(personalAttributeList);
    UserInfo userInf = new SamlUserInfo(personalAttributeList);
    if (userInfServ != null) {
        ((DefaultUserInfoService) userInfServ).addUserInfo(userInf);
    } else {
        LOG.error("marche pas injection GRRRRR !");
    }
    authTok.setAuthnResponse(authnResponse);
    ret = ((Authentication) authTok);
    return ret;
}

From source file:io.github.autsia.crowly.security.CrowlyAuthenticationManager.java

public void addUser(CrowlyUser user) throws AuthenticationException {
    String email = user.getEmail();
    if (userRepository.findByEmail(email) != null) {
        throw new BadCredentialsException(email + " is already used by another person.");
    }//from   w  w  w .  ja  v a2  s .  co m
    user.setRoles(Collections.singletonList(CrowlyRole.ROLE_USER.name()));
    user.setEnabled(true);
    user.setAccountNonExpired(true);
    user.setAccountNonLocked(true);
    user.setCredentialsNonExpired(true);
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    userRepository.save(user);
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.JWSAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

    JWSAuthenticationToken authRequest = (JWSAuthenticationToken) authentication;
    String token = authRequest.getJwsToken();
    Object messagePayload = authRequest.getPayload();
    if (StringUtils.isEmpty(token))
        throw new BadCredentialsException("Auth Token invalid");

    try {//from  w w w .ja  v a2s .c  o  m
        JWSObject jwsObject = JWSObject.parse(token);

        //We should test this comparation with binary payloads
        //Ensure message integrity
        if (!jwsObject.getPayload().toString().equals(messagePayload.toString())) {
            throw new BadCredentialsException("Invalid payload");
        }

        if (jwsObject.verify(verifier)) {
            Collection<GrantedAuthority> authoritiesDefault = new ArrayList<GrantedAuthority>();
            String[] roles = defaultRoles.split(",");
            for (String role : roles) {
                if (!StringUtils.isEmpty(role)) {
                    GrantedAuthority auth = new SimpleGrantedAuthority(defaultRoles);
                    authoritiesDefault.add(auth);
                }
            }

            if (userDetailsService != null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(cn);
                authoritiesDefault.addAll(userDetails.getAuthorities());
            }

            JWSAuthenticationToken authResult = new JWSAuthenticationToken((Object) cn, authoritiesDefault);

            if (logger.isDebugEnabled()) {
                logger.debug("CN: " + cn);
                logger.debug("Authentication success: " + authResult);
            }

            return authResult;
        }
    } catch (ParseException pe) {
        throw new BadCredentialsException("Invalid JWS Object", pe);
    } catch (UsernameNotFoundException unfe) {
        throw new BadCredentialsException("Auth Token invalid", unfe);
    } catch (Exception e) {
        throw new BadCredentialsException("Unknown error", e);
    }
    return null;

}

From source file:com.razorfish.security.AcceleratorAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : authentication.getName();//from   w w w  . j a v a 2  s .c o  m
    String usernameResult = username;

    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

    if (!usernameResult.isEmpty()) {
        final List<CustomerModel> result = getCustomerDao().findCustomerByMobileNumber(usernameResult);
        if (!result.isEmpty()) {
            usernameResult = result.iterator().next().getOriginalUid();
            token = new UsernamePasswordAuthenticationToken(usernameResult,
                    (String) authentication.getCredentials());
            token.setDetails(authentication.getDetails());
        }
    }

    if (getBruteForceAttackCounter().isAttack(usernameResult)) {
        try {
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(usernameResult));
            userModel.setLoginDisabled(true);
            getModelService().save(userModel);
            bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        } catch (final UnknownIdentifierException e) {
            LOG.warn("Brute force attack attempt for non existing user name " + usernameResult);
        } finally {
            throw new BadCredentialsException(
                    messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    checkCartForUser(usernameResult);
    return super.authenticate(token);
}

From source file:sk.lazyman.gizmo.security.GizmoAuthProvider.java

private Authentication authenticateUsingDb(Authentication authentication) throws AuthenticationException {
    String principal = (String) authentication.getPrincipal();
    String password = (String) ((UsernamePasswordAuthenticationToken) authentication).getCredentials();
    User user = userRepository.findUserByName(principal);
    if (user == null) {
        throw new BadCredentialsException("web.security.provider.invalid");
    }/*from  www . j  av  a 2 s .  co m*/

    if (user.getPassword() == null || !user.getPassword().equals(GizmoUtils.toSha1(password))) {
        throw new BadCredentialsException("GizmoAuthenticationProvider.userPasswordIncorrect");
    }

    if (!user.isEnabled()) {
        throw new BadCredentialsException("GizmoAuthenticationProvider.userDisabled");
    }

    GizmoPrincipal gizmoPrincipal = new GizmoPrincipal(user);

    LOGGER.debug("User '{}' authenticated ({}), authorities: {}", new Object[] { authentication.getPrincipal(),
            authentication.getClass().getSimpleName(), gizmoPrincipal.getAuthorities() });
    return new UsernamePasswordAuthenticationToken(gizmoPrincipal, null, gizmoPrincipal.getAuthorities());
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {//  www .  jav a2s . com
        Authentication credentials = extractCredentials(request);

        if (credentials != null) {

            if (debug) {
                logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
            }

            Authentication authResult = authenticationManager.authenticate(credentials);

            if (debug) {
                logger.debug("Authentication success: " + authResult.getName());
            }

            Authentication requestingPrincipal = SecurityContextHolder.getContext().getAuthentication();
            if (requestingPrincipal == null) {
                throw new BadCredentialsException(
                        "No client authentication found. Remember to put a filter upstream of the LoginAuthenticationFilter.");
            }

            String clientId = request.getParameter("client_id");
            if (null == clientId) {
                logger.error("No client_id in the request");
                throw new BadCredentialsException("No client_id in the request");
            }

            // Check that the client exists
            ClientDetails authenticatingClient = clientDetailsService.loadClientByClientId(clientId);
            if (authenticatingClient == null) {
                throw new BadCredentialsException("No client " + clientId + " found");
            }

            DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest(
                    getSingleValueMap(request), null, authenticatingClient.getClientId(), getScope(request));
            if (requestingPrincipal.isAuthenticated()) {
                // Ensure the OAuth2Authentication is authenticated
                authorizationRequest.setApproved(true);
            }

            SecurityContextHolder.getContext()
                    .setAuthentication(new OAuth2Authentication(authorizationRequest, authResult));

            onSuccessfulAuthentication(request, response, authResult);

        }

    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }

        onUnsuccessfulAuthentication(request, response, failed);

        authenticationEntryPoint.commence(request, response, failed);

        return;
    }

    chain.doFilter(request, response);
}

From source file:com.github.lynxdb.server.api.http.WebSecurityConfig.java

@Autowired
public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(new AbstractUserDetailsAuthenticationProvider() {
        @Override//from w w  w .j a  v  a2s.  c  o  m
        protected void additionalAuthenticationChecks(UserDetails ud, UsernamePasswordAuthenticationToken upat)
                throws AuthenticationException {

        }

        @Override
        protected UserDetails retrieveUser(String string, UsernamePasswordAuthenticationToken upat)
                throws AuthenticationException {
            User user = users.byLogin(string);
            if (user == null) {
                throw new UsernameNotFoundException("No such User : " + string);
            }
            if (user.checkPassword(upat.getCredentials().toString())) {
                return user;
            } else {
                throw new BadCredentialsException("Bad credentials");

            }
        }
    });
}