Example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken getCredentials

List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken getCredentials

Introduction

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

Prototype

public Object getCredentials() 

Source Link

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");
    }/*from   w w  w.  j  av  a  2s  .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: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");
    }/*ww  w.j  ava  2s .  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);
}

From source file:se.omegapoint.facepalm.client.security.DbAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    final String username = (String) token.getPrincipal();
    final String password = (String) token.getCredentials();

    final Optional<User> user = userRepository.findByNameAndPassword(username, password);

    return user.map(
            u -> new UsernamePasswordAuthenticationToken(new AuthenticatedUser(u.username), null, emptyList()))
            .orElse(null);//w w w  . j  a v  a  2 s  . com
}

From source file:com.springsource.greenhouse.account.UsernamePasswordAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    try {/*  www . j a  v  a2  s  .  c o  m*/
        Account account = accountRepository.authenticate(token.getName(), (String) token.getCredentials());
        return authenticatedToken(account, authentication);
    } catch (SignInNotFoundException e) {
        throw new org.springframework.security.core.userdetails.UsernameNotFoundException(token.getName(), e);
    } catch (InvalidPasswordException e) {
        throw new BadCredentialsException("Invalid password", e);
    }
}

From source file:security.MyAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
    String username = String.valueOf(auth.getPrincipal());
    String password = String.valueOf(auth.getCredentials());

    // 1. Use the username to load the data for the user, including authorities and password.
    User user = (User) userRepository.findOneByUsername(username);

    if (user == null)
        throw new BadCredentialsException("Bad Credentials");

    String saltPassword = Hashing.sha512().hashString(password + user.getSalt(), Charsets.UTF_8).toString();
    System.out.println("Salted pass: " + saltPassword);
    // 2. Check the passwords match.
    if (!user.getPassword().equals(saltPassword)) {
        throw new BadCredentialsException("Bad Credentials");
    }//  ww  w. j  a  v  a 2 s .  c  o  m

    // 3. Preferably clear the password in the user object before storing in authentication object
    //user.clearPassword();

    // 4. Return an authenticated token, containing user data and authorities  
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

    Authentication token = new UsernamePasswordAuthenticationToken(user, saltPassword, authorities);
    return token;
}

From source file:com.blstream.patronage.ctf.security.RestAuthenticationProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    Object salt = saltSource.getSalt(userDetails);

    if (authentication.getCredentials() == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("Authentication failed: no credentials provided");
        }/*from  www .j a v a2 s .  co m*/
        throw new BadCredentialsException("Authentication failed: no credentials provided");
    }

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

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("User %s credentials provided: %s, userDetails credentials: %s, salt: %s",
                userDetails.getUsername(), presentedPassword, userDetails.getPassword(), salt));
    }

    // TODO: make user's password encrypted!
    // if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
    if (!userDetails.getPassword().equals(presentedPassword)) {
        if (logger.isWarnEnabled()) {
            logger.warn("Authentication failed: password does not match stored value");
        }
        throw new BadCredentialsException("Authentication failed: password does not match stored value");
    }

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("User: %s authenticated successfully.", userDetails.getUsername()));
    }
}

From source file:org.axonframework.samples.trader.webui.security.TraderAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }/*w  w w  . j ava  2  s  . co m*/
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String password = String.valueOf(token.getCredentials());
    FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>();
    AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray());
    try {
        commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback);
        // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before
        // the command is dispatched.
    } catch (StructuralCommandValidationFailedException e) {
        return null;
    }
    UserAccount account;
    try {
        account = accountCallback.get();
        if (account == null) {
            throw new BadCredentialsException("Invalid username and/or password");
        }
    } catch (InterruptedException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    } catch (ExecutionException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account,
            authentication.getCredentials(), userAuthorities);
    result.setDetails(authentication.getDetails());
    return result;
}

From source file:com.ai.bss.webui.security.AiBssAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }//from  w w  w .  j a  v a 2s.c o  m
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String password = String.valueOf(token.getCredentials());
    FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>();
    AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray());
    try {
        //            commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback);
        // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before
        // the command is dispatched.
    } catch (StructuralCommandValidationFailedException e) {
        e.printStackTrace();
        return null;
    }
    UserAccount account;
    try {
        account = accountCallback.get();
        if (account == null) {
            throw new BadCredentialsException("Invalid username and/or password");
        }
    } catch (InterruptedException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    } catch (ExecutionException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account,
            authentication.getCredentials(), userAuthorities);
    result.setDetails(authentication.getDetails());
    return result;
}

From source file:org.jasig.schedassist.web.security.CustomLDAPAuthenticationProvider.java

/**
 * Incorporates some of the //w ww  . ja  va 2s .  c  o  m
 *  (non-Javadoc)
 * @see org.springframework.security.authentication.dao.DaoAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails, org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
 */
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request for user: " + username);
    }

    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(
                messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    try {
        DirContextOperations userData = getAuthenticator().authenticate(authentication);
        if (userData == null) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    } catch (PasswordPolicyException ppe) {
        // The only reason a ppolicy exception can occur during a bind is that the account is locked.
        throw new LockedException(
                messages.getMessage(ppe.getStatus().getErrorCode(), ppe.getStatus().getDefaultMessage()));
    } catch (UsernameNotFoundException notFound) {
        if (hideUserNotFoundExceptions) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            throw notFound;
        }
    }
}

From source file:de.kaiserpfalzEdv.office.ui.web.security.KPOfficeAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    KPOfficeUserDetail result;/*from  ww  w.  jav  a 2s.c om*/

    try {
        OfficeLoginTicket ticket = service.login(username, (String) authentication.getCredentials());

        result = new KPOfficeUserDetail(ticket);
    } catch (InvalidLoginException e) {
        throw new UsernameNotFoundException("Username '" + username + "' not found.");
    } catch (NoSuchAccountException e) {
        throw new BadCredentialsException("Wrong password for '" + username + "'.");
    }

    LOG.info("Created: {}", result);
    return result;
}