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

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

Introduction

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

Prototype

public Object getDetails() 

Source Link

Usage

From source file:whitelabel.cloud.webapp.security.spring.CloudUserDetailsAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {

    CloudWebAutenticationDetails details = ((CloudWebAutenticationDetails) authentication.getDetails());

    WsEndUserClient wsEndUser = new WsEndUserClient(wsEndUserNamespace, wsEndUserServiceName,
            details.getDatacenterUrl() + wsEndUserEndpoint);
    AppUserToken utoken = null;/*from ww  w .ja  v a 2s  . c o  m*/
    try {
        utoken = wsEndUser.loginAs(username, authentication.getCredentials().toString());
    } catch (Exception e) {
        throw new UsernameNotFoundException("USERNAME_NOT_FOUND", e);
    }

    if (utoken == null || !utoken.isValid()) {
        throw new UsernameNotFoundException("USERNAME_NOT_FOUND");
    }
    // create new cloud-user
    CloudUser cu = new CloudUser(username, authentication.getCredentials().toString(),
            details.getDatacenterId());
    // set di wsEndUser to the user (so every ws-invoke use same authentication token)
    cu.setWsEndUser(wsEndUser);

    try {
        //find VDCResourceConfiguration
        WsEndUserVDCConfigClient wsEndUserVDCConfigClient = new WsEndUserVDCConfigClient(wsEndUserNamespace,
                wsEndUserServiceName, details.getDatacenterUrl() + wsEndUserEndpoint);
        wsEndUserVDCConfigClient.setCredentials(utoken.getUserName(), utoken.getToken());
        cu.setVdcResourceBoundConfig(wsEndUserVDCConfigClient.getVDCResourceConfiguration());
    } catch (Exception e) {
        throw new UsernameNotFoundException("VDC_CONFIG_NOT_FOUND", e);
    }

    return new UserDetailsImpl(cu);

}

From source file:org.glassmaker.spring.web.MirrorTemplate.java

private Credential getCredential() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) auth;
    String accessToken = (String) token.getDetails();
    GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
    return credential;
}

From source file:com.orange.clara.tool.service.SsoUserDetailsService.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken)
        throws AuthenticationException, InvalidTokenException {
    OAuth2Authentication oAuth2Authentication = super.loadAuthentication(accessToken);
    UsernamePasswordAuthenticationToken userAuthentication = (UsernamePasswordAuthenticationToken) oAuth2Authentication
            .getUserAuthentication();//www  .j  a va2s  . c o  m
    User user = this.getUser((Map<String, Object>) userAuthentication.getDetails());
    Principal principal = () -> user.getUuid();
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "N/A",
            this.getGrantedAuthorities(user.getRoles()));
    token.setDetails(this.generateDetailsFromUser(user));
    OAuth2Request request = new OAuth2Request(null, this.finalClientId, null, true, null, null, null, null,
            null);

    return new OAuth2Authentication(request, token);
}

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

@Override
@Nonnull/*from w  w w. jav  a 2 s. com*/
@PerfLogged
protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken token) {
    try {
        return retrieveUser(username, token.getDetails());
    } catch (AuthenticationException e) {
        throw e;
    } catch (Exception e) {
        log.warn("unexpected failure in authentication", e);
        throw new AuthenticationServiceException("unexpected failure in authentication", e);
    }
}

From source file:org.glassmaker.spring.oauth.OAuth2AuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }//w w  w.  j  a  v a 2 s  .c  o  m
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        UserDetails userDetails = userDetailsService.loadUserByUsername((String) token.getPrincipal());
        UsernamePasswordAuthenticationToken newToken = new UsernamePasswordAuthenticationToken(
                token.getPrincipal(), token.getCredentials(), userDetails.getAuthorities());
        newToken.setDetails(token.getDetails());
        return newToken;
    }
    return null;
}

From source file:fr.univrouen.poste.provider.DatabaseAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = BadCredentialsException.class)
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {

    UserDetails userDetails = null;//from ww w  . j av  a2s  .  c  om

    logger.debug("Inside retrieveUser");

    WebAuthenticationDetails wad = (WebAuthenticationDetails) authentication.getDetails();
    String userIPAddress = wad.getRemoteAddress();

    Boolean ipCanBeUsed4AuthAdminManager = this.isIpCanBeUsed4AuthAdminManager(userIPAddress);

    username = username.toLowerCase();

    String password = (String) authentication.getCredentials();
    if (!StringUtils.hasText(password) || !StringUtils.hasText(username)) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Merci de saisir votre email et mot de passe");
    }
    String encryptedPassword = messageDigestPasswordEncoder.encodePassword(password, null);
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    Boolean enabled;

    try {
        TypedQuery<User> query = User.findUsersByEmailAddress(username, null, null);

        User targetUser = (User) query.getSingleResult();

        if (targetUser.isLocked()) {
            throw new BadCredentialsException("Compte vrouill, merci de retenter d'ici quelques secondes.");
        }

        // authenticate the person
        String expectedPassword = targetUser.getPassword();
        if (!StringUtils.hasText(expectedPassword)) {
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            throw new BadCredentialsException("Aucun mot de passe pour " + username
                    + " n'est enregistr dans la base, merci d'activer votre compte via le lien d'activation envoy par email. Contactez un administrateur si problme.");
        }
        if (!encryptedPassword.equals(expectedPassword)) {
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            throw new BadCredentialsException("Email utilisateur ou mot de passe invalide.");
        }

        // restriction accs rseau
        if (!ipCanBeUsed4AuthAdminManager
                && (targetUser.getIsAdmin() || targetUser.getIsSuperManager() || targetUser.getIsManager())) {
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            logger.warn("User " + username
                    + " tried to access to his admin/manager/supermanager account from this IP "
                    + userIPAddress);
            throw new BadCredentialsException(
                    "Vous ne pouvez pas vous authentifier sur ce compte depuis cet accs rseau. Contactez un administrateur si problme.");
        }

        // restriction dates accs pour candidats et membres 
        boolean isCurrentTimeOk4ThisCandidat = dateClotureChecker.isCurrentTimeOk4ThisCandidat(targetUser);
        boolean isCurrentTimeOk4ThisMembre = dateClotureChecker.isCurrentTimeOk4ThisMembre(targetUser);
        if ((targetUser.getIsCandidat() || targetUser.getIsMembre()) && !isCurrentTimeOk4ThisCandidat
                && !isCurrentTimeOk4ThisMembre) {
            if (targetUser.getIsCandidat() && !isCurrentTimeOk4ThisCandidat) {
                logger.warn("User " + username
                        + " tried to access to his candidat account but the dateEndCandidat is < current time");
            }
            if (targetUser.getIsMembre() && !isCurrentTimeOk4ThisMembre) {
                logger.warn("User " + username
                        + " tried to access to his membre account but the dateEndMembre is < current time");
            }
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            throw new BadCredentialsException(
                    "La date de clture des dpts est dpasse, vous ne pouvez maintenant plus accder  l'application.");
        }

        userDetails = databaseUserDetailsService.loadUserByUser(targetUser);

    } catch (EmptyResultDataAccessException e) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Compte utilisateur et/ou mot de passe invalide");
    } catch (EntityNotFoundException e) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Compte utilisateur et/ou mot de passe invalide");
    } catch (NonUniqueResultException e) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Utilisateur non unique, contactez l'administrateur.");
    }

    logService.logActionAuth(LogService.AUTH_SUCCESS, username, userIPAddress);

    return userDetails;
}

From source file:org.duracloud.account.security.auth.AuthProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    super.additionalAuthenticationChecks(userDetails, authentication);

    DuracloudUser dcUser = (DuracloudUser) userDetails;
    String userIpLimits = dcUser.getAllowableIPAddressRange();

    // if user IP limits are set, check request IP
    if (null != userIpLimits && !userIpLimits.equals("")) {
        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        String requestIp = details.getRemoteAddress();

        String[] ipLimits = userIpLimits.split(";");
        for (String ipLimit : ipLimits) {
            if (ipInRange(requestIp, ipLimit)) {
                // User's IP is within this range, grant access
                log.debug("Allowing authentication check to continue for user " + dcUser.getUsername()
                        + " because their IP " + requestIp + " exists in a valid range " + ipLimit);
                return;
            }/*  w w w  .ja v a 2  s.  c  o  m*/
        }

        // There are IP limits, and none of them match the user's IP, deny
        log.debug("Denying authentication request for user " + dcUser.getUsername() + " because their IP "
                + requestIp + " does not match any valid ranges " + userIpLimits);
        throw new InsufficientAuthenticationException(
                "Originating IP for authentication request" + requestIp + " is not in an accepted range.");
    } else { // No user IP limits, which means all IPs are accepted
        log.debug("Allowing authentication check to continue for user " + dcUser.getUsername()
                + " because no IP limits are defined");
        return;
    }
}

From source file:fr.xebia.springframework.security.core.providers.ExtendedDaoAuthenticationProvider.java

/**
 * Checks that the {@link org.springframework.security.web.authentication.WebAuthenticationDetails#getRemoteAddress()}
 * matches one of the {@link ExtendedUser#getAllowedRemoteAddresses()}. If
 * the given <code>userDetails</code> is not an {@link ExtendedUser} of if
 * the given <code>authentication.details</code> is not a
 * {@link org.springframework.security.web.authentication.WebAuthenticationDetails}, then the ip address check is silently
 * by passed.//ww w . j a  v a 2 s. co m
 */
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    super.additionalAuthenticationChecks(userDetails, authentication);

    if (!(userDetails instanceof ExtendedUser)) {
        if (log.isDebugEnabled()) {
            log.debug("Given userDetails '" + userDetails
                    + "' is not an ExtendedUser, skip ipAddress verification");
        }
        return;
    }
    ExtendedUser extendedUser = (ExtendedUser) userDetails;

    if (!(authentication.getDetails() instanceof WebAuthenticationDetails)) {
        if (log.isDebugEnabled()) {
            log.debug("Given authentication '" + authentication
                    + "' does not hold WebAuthenticationDetails, skip ipAddress verification");
        }
        return;
    }
    WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) authentication.getDetails();

    String remoteIpAddress = webAuthenticationDetails.getRemoteAddress();

    if (log.isDebugEnabled()) {
        log.debug("Evaluate permission for '" + extendedUser + "' to authenticate from ip address "
                + remoteIpAddress);
    }

    List<Pattern> allowedRemoteAddressesPatterns = extendedUser.getAllowedRemoteAddressesPatterns();
    if (!matchesOneAddress(remoteIpAddress, allowedRemoteAddressesPatterns)) {
        throw new BadCredentialsException("Access denied from IP : " + remoteIpAddress);
    }
}

From source file:org.duracloud.account.security.auth.AuthProviderTest.java

private boolean testIpAuthChecks(String remoteAddress) {
    AuthProvider authProvider = new AuthProvider(null, new ShaPasswordEncoder(256));

    String username = "user";
    String password = "pass";
    String passwordHash = "d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1";
    String ipLimits = "1.2.3.4/32;1.2.5.6/30";

    DuracloudUser userDetails = EasyMock.createMock(DuracloudUser.class);
    WebAuthenticationDetails webAuthDetails = EasyMock.createMock(WebAuthenticationDetails.class);
    UsernamePasswordAuthenticationToken authToken = EasyMock
            .createMock(UsernamePasswordAuthenticationToken.class);

    // Calls which occur as part of the call to super.additionalAuthenticationChecks()
    EasyMock.expect(authToken.getCredentials()).andReturn(password).times(2);
    EasyMock.expect(userDetails.getPassword()).andReturn(passwordHash).times(1);

    // Direct calls expected
    EasyMock.expect(userDetails.getAllowableIPAddressRange()).andReturn(ipLimits).times(1);
    EasyMock.expect(userDetails.getUsername()).andReturn(username).times(1);
    EasyMock.expect(authToken.getDetails()).andReturn(webAuthDetails).times(1);
    EasyMock.expect(webAuthDetails.getRemoteAddress()).andReturn(remoteAddress).times(1);

    EasyMock.replay(userDetails, webAuthDetails, authToken);

    boolean authAllowed = true;
    try {/*from  w  w w  .ja v  a  2s  .c  o  m*/
        authProvider.additionalAuthenticationChecks(userDetails, authToken);
    } catch (InsufficientAuthenticationException e) {
        authAllowed = false;
    }

    EasyMock.verify(userDetails, webAuthDetails, authToken);
    return authAllowed;
}

From source file:org.brekka.pegasus.core.security.UnlockAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(final String token, final UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    Object credentials = authentication.getCredentials();
    String password = credentials.toString();
    if (StringUtils.isBlank(password)) {
        throw new BadCredentialsException("A code is required");
    }//from   ww  w  .j a  va 2  s  .com

    AnonymousTransferUser anonymousTransferUser = new AnonymousTransferUser(token);
    SecurityContext context = SecurityContextHolder.getContext();

    // Temporarily bind the authentication user to the security context so that we can do the unlock
    // this is primarily for the EventService to capture the IP/remote user.
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(anonymousTransferUser,
            anonymousTransferUser);
    auth.setDetails(authentication.getDetails());
    try {
        context.setAuthentication(auth);
        anonymousService.unlock(token, password, true);
        context.setAuthentication(null);
        return anonymousTransferUser;
    } catch (PhalanxException e) {
        if (e.getErrorCode() == PhalanxErrorCode.CP302) {
            throw new BadCredentialsException("Code appears to be incorrect");
        }
        throw e;
    }
}