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.corporate.transport.authentication.FacebookAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) {

    System.out.println("FacebookAuthenticationProvider.authenticate()");

    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;

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

    //TEST      // ww  w. j av  a2 s.  c  om
    try {
        System.out.println("GOING FOR VALIDATION");
        LDAPAuthentication ldap = new LDAPAuthentication();
        if (ldap.authenticate(username, password)) {
            List<GrantedAuthority> grantedAuthoritiesList = new ArrayList<GrantedAuthority>();

            if (username != null && (username.equals("patel286@avaya.com"))) {
                grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
            } else {
                grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_USER"));
            }

            return new UsernamePasswordAuthenticationToken(username, null, grantedAuthoritiesList);
        }

    } catch (Exception e) {

        if (e instanceof AuthenticationException) {
            throw new BadCredentialsException("Incorrect Email Id or Password - Jayesh");
        }
        //TODO [SM] Add logging for specific exception
        else if (e instanceof CommunicationException) {
            throw new LDAPConnectivityException("There is some error connecting with LDAP");
        } else if (e instanceof NamingException) {
            throw new LDAPConnectivityException("There is some error connecting with LDAP");
        } else {
            throw new LDAPConnectivityException("There is some error connecting with LDAP");
        }
    }

    //PRODUCTION      
    /*      try{
       System.out.println("GOING FOR VALIDATION");
       com.corporate.ldap.Authentication ldap = new com.corporate.ldap.Authentication();
       status = ldap.authenticate(username, password);
            
       System.out.println("GOING FOR VALIDATION STATUS:"+status);
       if(status==1){
    List<GrantedAuthority> grantedAuthoritiesList = new ArrayList<GrantedAuthority>();
            
    if(username!=null && username.equals("jayesh.patel")){
       grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));   
    }else{
       grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_USER"));
    }
            
    return new UsernamePasswordAuthenticationToken(username, null, grantedAuthoritiesList);
            
       }else if(status==0){
    throw new BadCredentialsException("Incorrect Email Id or Password.");
            
       }else if(status==2){
    throw new LDAPConnectivityException("There is some error connecting with LDAP");
       }
            
    }catch (Exception e) {
       e.printStackTrace();
    }*/

    return null;

}

From source file:org.cloudfoundry.identity.uaa.login.AutologinController.java

@RequestMapping(value = "/autologin", method = RequestMethod.POST)
@ResponseBody//w  w  w  .  ja  va  2 s  . c o m
public AutologinResponse generateAutologinCode(@RequestBody AutologinRequest request) throws Exception {
    String username = request.getUsername();
    if (username == null) {
        throw new BadCredentialsException("No username in request");
    }
    if (authenticationManager != null) {
        String password = request.getPassword();
        if (!StringUtils.hasText(password)) {
            throw new BadCredentialsException("No password in request");
        }
        authenticationManager.authenticate(new AuthzAuthenticationRequest(username, password, null));
    }
    logger.info("Autologin authentication request for " + username);
    SocialClientUserDetails user = new SocialClientUserDetails(username, UaaAuthority.USER_AUTHORITIES);
    return new AutologinResponse(codeStore.storeUser(user));
}

From source file:com.capinfo.common.security.authentication.dao.SecurityDaoAuthenticationProvider.java

/**
 * ?org.springframework.security.authentication.dao.
 * AbstractUserDetailsAuthenticationProvider.authenticate
 * //www .  j  a  va  2s . c om
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    // Determine username  credentials
    String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();

    boolean cacheWasUsed = true;
    UserDetails user = getUserCache().getUserFromCache(username);
    // Ehcache?UserDetailspasswordnull.usernamepassword?
    // boolean userOutCache=user == null;
    boolean userOutCache = user == null || StringUtils.isBlank(user.getUsername())
            || StringUtils.isBlank(user.getPassword());
    if (userOutCache) {
        cacheWasUsed = false;

        try {
            user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);

            if (!authentication.getCredentials().toString().equals(user.getPassword())) {
                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
        } catch (UsernameNotFoundException notFound) {
            logger.debug("User '" + username + "' not found");

            if (hideUserNotFoundExceptions) {
                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            } else {
                throw notFound;
            }
        }

        Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
    }

    try {
        getPreAuthenticationChecks().check(user);
    } catch (AuthenticationException exception) {
        if (cacheWasUsed) {
            // There was a problem, so try again after checking
            // we're using latest data (i.e. not from the cache)
            cacheWasUsed = false;
            user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
            getPreAuthenticationChecks().check(user);
        } else {
            throw exception;
        }
    }

    getPostAuthenticationChecks().check(user);

    if (!cacheWasUsed) {
        getUserCache().putUserInCache(user);
        UserDetails user2 = getUserCache().getUserFromCache(username);
    }

    Object principalToReturn = user;

    if (isForcePrincipalAsString()) {
        principalToReturn = user.getUsername();
    }

    return createSuccessAuthentication(principalToReturn, authentication, user);
}

From source file:org.cloudfoundry.identity.uaa.error.JsonAwareAuthenticationEntryPointTests.java

@Test
public void testCommenceWithHtmlAndJsonAccept() throws Exception {
    request.addHeader("Accept", String.format("%s,%s", MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_JSON));
    entryPoint.commence(request, response, new BadCredentialsException("Bad"));
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals(null, response.getErrorMessage());
}

From source file:nc.noumea.mairie.appock.core.security.AppockAuthenticationProvider.java

/**
 * Override la mthode authenticate/*  w ww.  j a v  a 2  s .com*/
 * 
 * @param authentication Authentication
 * @throws AuthenticationException Exception d'authentification
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    Authentication authenticationResult = null;

    if (provider != null)
        try {
            authenticationResult = provider.authenticate(authentication);
        } catch (BadCredentialsException e) {
            LOGGER.error("Error lors de l'authentification", e);
            throw new BadCredentialsException(messageProvider);
        }

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    List<GrantedAuthority> roles = new ArrayList<>();

    try {
        AppUser appUser = appUserService.findByLogin(username);
        if (appUser == null || !appUser.isActif()) {
            throw new BadCredentialsException(messageAppock);
        }
    } catch (NoResultException e) {
        throw new BadCredentialsException(messageAppock);
    }

    return (provider == null) ? new UsernamePasswordAuthenticationToken(username, password, roles)
            : authenticationResult;
}

From source file:com.epam.training.storefront.security.AcceleratorAuthenticationProvider.java

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

    CustomerModel userModel = null;
    try {
        userModel = (CustomerModel) getUserService().getUserForUID(StringUtils.lowerCase(username));
    } catch (final UnknownIdentifierException e) {
        LOG.warn("Brute force attack attempt for non existing user name " + username);
    }
    if (userModel == null) {
        throw new BadCredentialsException("Bad credentials");
    }

    if (getBruteForceAttackCounter().isAttack(username)) {
        userModel.setLoginDisabled(true);
        userModel.setStatus(Boolean.TRUE);
        userModel.setAttemptCount(0);
        getModelService().save(userModel);
        bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        throw new LockedException("Locked account");
    } else {
        userModel.setAttemptCount(bruteForceAttackCounter.getUserFailedLogins(username));
        getModelService().save(userModel);
    }

    return super.authenticate(authentication);

}

From source file:net.firejack.platform.web.security.spring.openid.OpenIDAuthenticationManager.java

@Override
protected Authentication doAuthentication(Authentication authentication) throws AuthenticationException {
    if (authentication instanceof OpenIDAuthenticationToken) {
        OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) authentication;
        if (!OpenIDAuthenticationStatus.SUCCESS.equals(token.getStatus())) {
            String errorMessage = MessageResolver.messageFormatting("login.wrong.credentials", null);
            throw new BadCredentialsException(errorMessage);
        }/*w ww  . j  a  v a2  s.c  o m*/
        String email = findAttributeValueByName(SupportedOpenIDAttribute.EMAIL, token.getAttributes());
        if (StringUtils.isBlank(email)) {
            String errorMessage = MessageResolver.messageFormatting("login.wrong.credentials", null);
            throw new BadCredentialsException(errorMessage);
        }

        HttpSession session = ((SessionContainerWebAuthenticationDetails) token.getDetails()).getSession();

        if (authenticator != null) {
            AuthenticatorFactory authenticatorFactory = AuthenticatorFactory.getInstance();
            Map<SupportedOpenIDAttribute, String> attributeValues = findAttributeValues(token.getAttributes());
            OpenIDAuthenticationSource openIDAuthenticationSource = (OpenIDAuthenticationSource) authenticatorFactory
                    .provideOpenIDAuthenticationSource(email, attributeValues);
            IAuthenticationDetails authenticationDetails = authenticator
                    .authenticate(openIDAuthenticationSource);
            if (authenticationDetails != null) {
                return generateDefaultToken(authenticationDetails, session);
            }
        }
    }

    String errorMessage = MessageResolver.messageFormatting("login.authentication.failure", null);
    throw new BadCredentialsException(errorMessage);
}

From source file:oauth2.authentication.UserAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = AuthenticationException.class)
public Authentication authenticate(Authentication authentication) {
    checkNotNull(authentication);//from w  ww . j a  v  a  2 s  . com
    String userId = authentication.getName();
    User user = userRepository.findByUserId(userId);
    if (user == null) {
        LOGGER.debug("User {} not found", userId);
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    try {
        authenticationStrategy.authenticate(user, authentication.getCredentials());
        user.getLoginStatus().loginSuccessful(Instant.now());
        Set<GrantedAuthority> authorities = mapAuthorities(user);
        return createSuccessAuthentication(authentication.getPrincipal(), authentication, authorities);
    } catch (BadCredentialsException ex) {
        user.getLoginStatus().loginFailed(Instant.now());
        throw ex;
    }
}

From source file:org.awesomeagile.testing.hackpad.FakeHackpadController.java

@RequestMapping(value = "/api/1.0/pad/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody/*from   w  w  w.  j  av  a 2  s  . c  o  m*/
public PadIdentity createHackpad(@RequestBody String content, @RequestParam("oauth_consumer_key") String key) {
    if (!clientId.equals(key)) {
        throw new BadCredentialsException("Invalid client ID: " + key);
    }
    PadIdentity padIdentity = new PadIdentity(RandomStringUtils.randomAlphanumeric(8));
    hackpads.put(padIdentity, content);
    return padIdentity;
}

From source file:net.przemkovv.sphinx.service.UserService.java

@Transactional(readOnly = false)
//    @Secured({Role.UzytkownicyZmianaHasla})
public void changePassword(User user, String oldPassword, String newPassword) {
    String oldPasswordHash = createHash(oldPassword);
    String newPasswordHash = createHash(newPassword);
    if (user.getPassword().isEmpty() && oldPassword.isEmpty()) {
        user.setPassword(newPasswordHash);
    } else if (user.getPassword().equals(oldPasswordHash)) {
        user.setPassword(newPasswordHash);
    } else {//from w  ww  .jav a2 s.  c  o m
        throw new BadCredentialsException(
                "Cannot change password. Invalid old password or no sufficient permissions.");
    }
    userDAO.update(user);

}