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:com.hp.autonomy.frontend.configuration.authentication.CommunityAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final com.hp.autonomy.frontend.configuration.authentication.Authentication<?> authenticationConfig = configService
            .getConfig().getAuthentication();
    final String authenticationMethod = authenticationConfig.getMethod();

    if (!(authenticationConfig instanceof CommunityAuthentication)
            || LoginTypes.DEFAULT.equals(authenticationMethod)) {
        return null;
    }/*from   w  w w  .  j  av a  2 s  .c o m*/

    final String username = authentication.getName();
    final String password = authentication.getCredentials().toString();

    try {
        final boolean isAuthenticated = userService.authenticateUser(username, password, authenticationMethod);

        if (!isAuthenticated) {
            throw new BadCredentialsException("Bad credentials");
        }

        final UserRoles userRoles = userService.getUser(username, true);
        Set<String> roleNames = new HashSet<>(userRoles.getRoles());

        if (!roles.areRolesAuthorized(roleNames, loginPrivileges)) {
            // if we have default roles, grant the user the default roles
            if (!defaultRoles.isEmpty()) {
                roleNames = defaultRoles;

                // check that the default role names make sense
                if (!roles.areRolesAuthorized(roleNames, loginPrivileges)) {
                    throw new BadCredentialsException("Bad credentials");
                }
            } else {
                throw new BadCredentialsException("Bad credentials");
            }
        }

        final Collection<GrantedAuthority> grantedAuthorities = roleNames.stream()
                .map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        final Collection<? extends GrantedAuthority> mappedAuthorities = authoritiesMapper
                .mapAuthorities(grantedAuthorities);

        return new UsernamePasswordAuthenticationToken(
                new CommunityPrincipal(userRoles.getUid(), username, userRoles.getSecurityInfo(), roleNames),
                password, mappedAuthorities);
    } catch (final AciErrorException aciError) {
        // This should not happen
        throw new InternalAuthenticationServiceException(
                "An ACI error occurred while attempting to authenticate", aciError);
    } catch (final AciServiceException serviceError) {
        // This will happen if community is down
        throw new InternalAuthenticationServiceException("An error occurred while contacting community",
                serviceError);
    }
}

From source file:org.taverna.server.master.identity.StrippedDownAuthProvider.java

/**
 * Creates a successful {@link Authentication} object.
 * <p>//from   w  ww . j a  v a2s. co m
 * Protected so subclasses can override.
 * </p>
 * <p>
 * Subclasses will usually store the original credentials the user supplied
 * (not salted or encoded passwords) in the returned
 * <code>Authentication</code> object.
 * </p>
 * 
 * @param principal
 *            that should be the principal in the returned object (defined
 *            by the {@link #isForcePrincipalAsString()} method)
 * @param authentication
 *            that was presented to the provider for validation
 * @param user
 *            that was loaded by the implementation
 * 
 * @return the successful authentication token
 */
private Authentication createSuccessAuthentication(Object principal, Authentication authentication,
        UserDetails user) {
    /*
     * Ensure we return the original credentials the user supplied, so
     * subsequent attempts are successful even with encoded passwords. Also
     * ensure we return the original getDetails(), so that future
     * authentication events after cache expiry contain the details
     */
    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal,
            authentication.getCredentials(), user.getAuthorities());
    result.setDetails(authentication.getDetails());

    return result;
}

From source file:com.ctb.prism.login.security.provider.AbstractUserDetailsAuthenticationProvider.java

/**
 * Creates a successful {@link Authentication} object.<p>Protected so subclasses can override.</p>
 *  <p>Subclasses will usually store the original credentials the user supplied (not salted or encoded
 * passwords) in the returned <code>Authentication</code> object.</p>
 *
 * @param principal that should be the principal in the returned object (defined by the {@link
 *        #isForcePrincipalAsString()} method)
 * @param authentication that was presented to the provider for validation
 * @param user that was loaded by the implementation
 *
 * @return the successful authentication token
 *//*from w  w w .  j  a  va  2s .c o m*/
protected Authentication createSuccessAuthentication(Object principal, Authentication authentication,
        UserDetails user) {
    // Ensure we return the original credentials the user supplied,
    // so subsequent attempts are successful even with encoded passwords.
    // Also ensure we return the original getDetails(), so that future
    // authentication events after cache expiry contain the details
    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal,
            authentication.getCredentials(), authoritiesMapper.mapAuthorities(user.getAuthorities()));
    result.setDetails(authentication.getDetails());

    return result;
}

From source file:at.ac.univie.isc.asio.security.HttpMethodRestrictionFilter.java

/**
 * Copy the original authentication, but use the restricted set of authorities. Keep special token
 * classes, like Anonymous, RememberMe, etc. .
 */// w w  w.  jav a2s . c  o  m
private AbstractAuthenticationToken copy(final Authentication authentication,
        final Set<GrantedAuthority> restricted) {
    final AbstractAuthenticationToken replacement;
    if (authentication instanceof AnonymousAuthenticationToken) {
        replacement = new AnonymousAuthenticationToken("dummy-key", authentication.getPrincipal(), restricted);
    } else if (authentication instanceof RememberMeAuthenticationToken) {
        replacement = new RememberMeAuthenticationToken("dummy-key", authentication.getPrincipal(), restricted);
    } else if (authentication instanceof PreAuthenticatedAuthenticationToken) {
        replacement = new PreAuthenticatedAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), restricted);
    } else {
        replacement = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), restricted);
    }
    return replacement;
}

From source file:com.autoupdater.server.utils.authentication.BCryptAuthenticationManager.java

/**
 * Authenticate user.//  www. jav  a 2  s  .  c  o  m
 * 
 * @param auth
 *            authentication data passed by Spring Security
 * @return result of authentication
 */
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    logger.debug("Performing authentication");

    User user = null;

    logger.debug("Searching user [" + auth.getName() + "] in DB");
    try {
        user = userService.findByUsername(auth.getName());
    } catch (Exception e) {
        logger.error("User [" + auth.getName() + "] does not exists (exception)!");
        throw new AuthenticationServiceException("Error while obtaining User data!");
    }
    if (user == null) {
        logger.error("User [" + auth.getName() + "] does not exists (null)!");
        throw new BadCredentialsException("User does not exists!");
    }

    if (!BCrypt.checkpw(auth.getCredentials().toString(), user.getHashedPassword())) {
        logger.error("Password doesn't match!");
        throw new BadCredentialsException("Password doesn't match!");
    }

    logger.debug("User details are good and ready to go");
    return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(),
            getAuthorities(user.isAdmin(), user.isPackageAdmin()));
}

From source file:com.hp.autonomy.frontend.configuration.authentication.SingleUserAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final com.hp.autonomy.frontend.configuration.authentication.Authentication<?> configAuthentication = configService
            .getConfig().getAuthentication();

    if (!(configAuthentication instanceof SingleUserAuthentication)
            || LoginTypes.DEFAULT.equalsIgnoreCase(configAuthentication.getMethod())) {
        return null;
    }//from w  w  w. java  2s .  c om

    final SingleUserAuthentication singleUserAuthentication = (SingleUserAuthentication) configAuthentication;
    final BCryptUsernameAndPassword singleUser = singleUserAuthentication.getSingleUser();

    final String username = singleUser.getUsername();
    final String hashedPassword = singleUser.getHashedPassword();
    final String providedPassword = authentication.getCredentials().toString();

    if (authentication.getName().equals(username) && BCrypt.checkpw(providedPassword, hashedPassword)) {
        return new UsernamePasswordAuthenticationToken(username, providedPassword,
                Arrays.asList(new SimpleGrantedAuthority(roleAdmin)));
    } else {
        throw new BadCredentialsException("Bad credentials");
    }
}

From source file:org.valkyriercp.security.remoting.BasicAuthCommonsHttpInvokerProxyFactoryBean.java

/**
 * Handle a change in the current authentication token.
 * This method will fail fast if the executor isn't a CommonsHttpInvokerRequestExecutor.
 * @see org.valkyriercp.security.AuthenticationAware#setAuthenticationToken(org.springframework.security.core.Authentication)
 */// w  w  w  . j  ava2 s.c o m
public void setAuthenticationToken(Authentication authentication) {
    if (logger.isDebugEnabled()) {
        logger.debug("New authentication token: " + authentication);
    }

    HttpComponentsHttpInvokerRequestExecutor executor = (HttpComponentsHttpInvokerRequestExecutor) getHttpInvokerRequestExecutor();
    DefaultHttpClient httpClient = (DefaultHttpClient) executor.getHttpClient();
    BasicCredentialsProvider provider = new BasicCredentialsProvider();
    httpClient.setCredentialsProvider(provider);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor());
    UsernamePasswordCredentials usernamePasswordCredentials;
    if (authentication != null) {
        usernamePasswordCredentials = new UsernamePasswordCredentials(authentication.getName(),
                authentication.getCredentials().toString());
    } else {
        usernamePasswordCredentials = null;
    }
    provider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
}

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  ww w.  j  a  v  a 2 s  . co 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:de.thm.arsnova.service.UserServiceImpl.java

@Override
public de.thm.arsnova.model.ClientAuthentication getCurrentClientAuthentication() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || !(authentication.getPrincipal() instanceof User)) {
        return null;
    }//from  w  w w.  j  a  v a  2s.  c  om
    User user = (User) authentication.getPrincipal();
    String jwt = authentication instanceof JwtToken ? (String) authentication.getCredentials()
            : jwtService.createSignedToken(user);

    ClientAuthentication clientAuthentication = new ClientAuthentication(user.getId(), user.getUsername(),
            user.getAuthProvider(), jwt);

    return clientAuthentication;
}