Example usage for org.springframework.security.core Authentication getCredentials

List of usage examples for org.springframework.security.core Authentication getCredentials

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getCredentials.

Prototype

Object getCredentials();

Source Link

Document

The credentials that prove the principal is correct.

Usage

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");
    }/*from w  ww.  j  av  a2s .  c o  m*/

    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.evolveum.midpoint.web.security.MidPointAuthenticationProvider.java

private Authentication authenticateUser(MidPointPrincipal principal, Authentication authentication) {
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        return authenticateUserPassword(principal, (String) authentication.getCredentials());
    } else if (authentication instanceof PreAuthenticatedAuthenticationToken) {
        PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, null,
                principal.getAuthorities());
        return token;
    } else {/*  w w  w .j av a 2s. co  m*/
        throw new AuthenticationServiceException("web.security.provider.unavailable");
    }

}

From source file:de.theit.jenkins.crowd.CrowdAuthenticationManager.java

/**
 * {@inheritDoc}// w  w  w.j  av  a2s .co m
 * 
 * @see org.springframework.security.AuthenticationManager#authenticate(org.springframework.security.Authentication)
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getPrincipal().toString();

    // checking whether there's already a SSO token
    if (null == authentication.getCredentials() && authentication instanceof CrowdAuthenticationToken
            && null != ((CrowdAuthenticationToken) authentication).getSSOToken()) {
        // SSO token available => user already authenticated
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer("User '" + username + "' already authenticated");
        }
        return authentication;
    }

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

    // ensure that the group is available, active and that the user
    // is a member of it
    if (!this.configuration.isGroupMember(username)) {
        throw new InsufficientAuthenticationException(
                userNotValid(username, this.configuration.allowedGroupNames));
    }

    String displayName = null;
    try {
        // authenticate user
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Authenticating user: " + username);
        }
        User user = this.configuration.crowdClient.authenticateUser(username, password);
        displayName = user.getDisplayName();
    } catch (UserNotFoundException ex) {
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info(userNotFound(username));
        }
        throw new BadCredentialsException(userNotFound(username), ex);
    } catch (ExpiredCredentialException ex) {
        LOG.warning(expiredCredentials(username));
        throw new CredentialsExpiredException(expiredCredentials(username), ex);
    } catch (InactiveAccountException ex) {
        LOG.warning(accountExpired(username));
        throw new AccountExpiredException(accountExpired(username), ex);
    } catch (ApplicationPermissionException ex) {
        LOG.warning(applicationPermission());
        throw new AuthenticationServiceException(applicationPermission(), ex);
    } catch (InvalidAuthenticationException ex) {
        LOG.warning(invalidAuthentication());
        throw new AuthenticationServiceException(invalidAuthentication(), ex);
    } catch (OperationFailedException ex) {
        LOG.log(Level.SEVERE, operationFailed(), ex);
        throw new AuthenticationServiceException(operationFailed(), ex);
    }

    // user successfully authenticated
    // => retrieve the list of groups the user is a member of
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    // add the "authenticated" authority to the list of granted
    // authorities...
    authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
    // ..and finally all authorities retrieved from the Crowd server
    authorities.addAll(this.configuration.getAuthoritiesForUser(username));

    // user successfully authenticated => create authentication token
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("User successfully authenticated; creating authentication token");
    }

    return new CrowdAuthenticationToken(username, password, authorities, null, displayName);
}

From source file:org.carewebframework.security.spring.AbstractAuthenticationProvider.java

/**
 * Authentication Provider. Produces a trusted <code>UsernamePasswordAuthenticationToken</code>
 * if//from w  w  w. j av a  2  s.  c  o  m
 * 
 * @param authentication The authentication context.
 * @return authentication Authentication object if authentication succeeded. Null if not.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    CWFAuthenticationDetails details = (CWFAuthenticationDetails) authentication.getDetails();
    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();
    String domain = null;

    if (log.isDebugEnabled()) {
        log.debug("User: " + username);
        log.debug("Details, RA: " + details == null ? "null" : details.getRemoteAddress());
    }

    if (username != null) {
        String pcs[] = username.split("\\\\", 2);
        domain = pcs[0];
        username = pcs.length > 1 ? pcs[1] : null;
    }

    ISecurityDomain securityDomain = domain == null ? null
            : SecurityUtil.getSecurityService().getSecurityDomain(domain);

    if (username == null || password == null || securityDomain == null) {
        throw new BadCredentialsException("Missing security credentials.");
    }

    IUser user = authenticate(username, password, securityDomain, details);
    details.setDetail("user", user);
    List<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>();
    List<String> list = getAuthorities(user);
    Set<String> authorities = list == null ? new HashSet<String>() : new HashSet<String>(list);

    for (String grantedAuthority : grantedAuthorities) {
        if (grantedAuthority.startsWith("-")) {
            authorities.remove(grantedAuthority.substring(1));
        } else {
            authorities.add(grantedAuthority);
        }
    }

    for (String authority : authorities) {
        if (!authority.isEmpty()) {
            userAuthorities.add(new SimpleGrantedAuthority(authority));
        }
    }

    User principal = new User(username, password, true, true, true, true, userAuthorities);

    authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
            principal.getAuthorities());
    ((UsernamePasswordAuthenticationToken) authentication).setDetails(details);
    return authentication;
}

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   ww  w  .jav a 2  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:eu.supersede.fe.security.SecurityConfiguration.java

@Bean
AuthenticationProvider customAuthenticationProvider() {
    return new AuthenticationProvider() {
        private final Logger log = LoggerFactory.getLogger(this.getClass());

        @Override//ww w. j  a  va2s  . com
        @Transactional
        public Authentication authenticate(Authentication auth) throws AuthenticationException {
            String username = (String) auth.getPrincipal();
            String password = (String) auth.getCredentials();

            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            HttpServletRequest req = attr.getRequest();
            String tenantId = req.getHeader("TenantId");

            if (tenantId == null) {
                log.error("Tenant provided");
                throw new BadCredentialsException("Invalid login request: missing tenant");
            }

            AuthorizationToken token = getAuthToken(username, password, tenantId);
            User user = users.findByUsername(username);

            if (user == null) {
                log.error("Username not found in Database");
                throw new BadCredentialsException("Invalid login request: user " + username + " not found");
            }

            // get authorities from profiles
            List<Profile> profiles = user.getProfiles();
            String[] authorities = new String[profiles.size()];

            for (int i = 0; i < profiles.size(); i++) {
                authorities[i] = "ROLE_" + profiles.get(i).getName();
            }

            log.debug("User has " + authorities.length + " authorities");

            List<GrantedAuthority> permissions = AuthorityUtils.createAuthorityList(authorities);
            DatabaseUser dbUser = new DatabaseUser(user.getUserId(),
                    user.getFirstName() + " " + user.getLastName(), user.getEmail(), password, token, true,
                    true, true, true, permissions, user.getLocale());

            return new UsernamePasswordAuthenticationToken(dbUser, password, permissions);// AUTHORITIES
        }

        private AuthorizationToken getAuthToken(String username, String password, String tenantId) {
            AuthorizationToken token = null;

            if (AUTH_MANAGER_ENABLED) {
                try {
                    token = proxy.getIFAuthenticationManager(tenantId).getAuthorizationToken(username, password,
                            tenantId);
                } catch (HttpClientErrorException e) {
                    log.error("Invalid username and password.");
                } catch (NullPointerException e1) {
                    log.error("Authorization token is null, check your if.properties file in the conf/ folder");
                } catch (Exception e2) {
                    e2.printStackTrace();
                }

                if (token == null || token.getAccessToken() == null) {
                    log.error("Supersede integration token is null");
                    throw new BadCredentialsException(
                            "Invalid login request: authentication manager token is null");
                }
            } else {
                log.warn("IF Authentication Manager disable, user token is NULL");
            }

            return token;
        }

        @Override
        @SuppressWarnings("rawtypes")
        public boolean supports(Class authentication) {
            return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
        }
    };
}

From source file:hr.foi.sis.conf.PBKDF2AuthProvider.java

@Override
public Authentication authenticate(Authentication a) throws AuthenticationException {

    String username = a.getName();

    Logger.getLogger("Auth").log(Level.INFO, "POST on login username -- " + username);

    if (username == null)
        throw new BadCredentialsException("Username not found.");

    String password = (String) a.getCredentials();

    Logger.getLogger("Auth").log(Level.INFO, "POST on password -- " + password);

    if (password == null)
        throw new BadCredentialsException("Password not found.");

    Logger.getLogger("Auth").log(Level.INFO, "Getting user from database");

    UserSaltDetails user = userService.loadUserByUsername(username);

    Logger.getLogger("Auth").log(Level.INFO, "User get with username: " + user.getUsername());

    Logger.getLogger("Auth").log(Level.INFO, "User get with password: " + user.getPassword());
    String pw = user.getPassword();

    Logger.getLogger("Auth").log(Level.INFO, "User get with salt : " + user.getUserSalt());

    Logger.getLogger("Auth").log(Level.INFO, "User get with authorities : " + user.getAuthorities().toString());

    boolean isAuthenticated = false;

    try {// w  w w. jav a  2s  .  co  m

        isAuthenticated = PBKDF2.authenticate(password, user.getPassword(), user.getUserSalt());
        Logger.getLogger("Auth").log(Level.INFO, "Is true : " + isAuthenticated);

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(PBKDF2AuthProvider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(PBKDF2AuthProvider.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (!isAuthenticated)
        throw new BadCredentialsException("Wrong password.");
    else
        Logger.getLogger("Auth").log(Level.INFO, "Authenticated");

    return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());

}

From source file:com.example.AuthenticationController.java

@PostMapping("/factor")
public void accept(@RequestParam String factor, Principal principal, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (!"red".equals(factor)) {
        response.sendRedirect("/factor?error=true");
        return;/*from w  w  w  .ja va 2  s  .c o  m*/
    }
    Authentication authentication = (Authentication) principal;
    Collection<GrantedAuthority> authorities = new ArrayList<>(authentication.getAuthorities());
    authorities.add(new SimpleGrantedAuthority("ROLE_FACTOR"));
    PreAuthenticatedAuthenticationToken successful = new PreAuthenticatedAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials(), authorities);
    successful.setDetails(authentication.getDetails());
    SecurityContextHolder.getContext().setAuthentication(successful);
    handler.onAuthenticationSuccess(request, response, successful);
}

From source file:com.companyname.providers.DAOAuthenticationProvider.java

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

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

    String credentials = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : (String) authentication.getCredentials();

    logger.info("platform: Start authenticating user [" + username + "]");

    try {//w w w .  j av a2s.c  om
        Authentication auth = null;

        // authenticate from cache first to enhance performance
        auth = cache.authenticateFromCache(authentication);

        // perform authentication against our user's database store
        if (auth != null && auth.isAuthenticated()) {
            logger.info("User [" + username + "] is successfully authenticated against the cache");
        } else {
            auth = super.authenticate(authentication);
            cache.add(auth);
            logger.info("User [" + username + "] is successfully authenticated against DB store");
        }

        // build platform authentication object
        Authentication platformAuthentication = PlatAuthentication.getPlatAuthentication(auth);
        ((PlatAuthentication) platformAuthentication).setUserCredentials(credentials);
        return platformAuthentication;

    } catch (AuthenticationException ex1) {
        logger.log(Level.SEVERE, "Unsuccessfully authenticating user [" + username + "] ", ex1);
    }

    return null;
}