Example usage for org.springframework.security.oauth2.provider OAuth2Authentication setAuthenticated

List of usage examples for org.springframework.security.oauth2.provider OAuth2Authentication setAuthenticated

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider OAuth2Authentication setAuthenticated.

Prototype

public void setAuthenticated(boolean authenticated) 

Source Link

Usage

From source file:org.cloudfoundry.identity.uaa.authentication.AbstractClientParametersAuthenticationFilter.java

private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo,
        String clientId) {/* w  w  w  .  java 2 s  .c o  m*/
    if (clientId != null) {
        Result policyResult = loginPolicy.isAllowed(clientId);
        if (!policyResult.isAllowed()) {
            throw new ClientLockoutException("Client " + clientId + " has " + policyResult.getFailureCount()
                    + " failed authentications within the last checking period.");
        }
    }

    String clientSecret = loginInfo.get(CLIENT_SECRET);
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId,
            clientSecret);
    authentication.setDetails(new UaaAuthenticationDetails(req, clientId));
    try {
        Authentication auth = clientAuthenticationManager.authenticate(authentication);
        if (auth == null || !auth.isAuthenticated()) {
            throw new BadCredentialsException("Client Authentication failed.");
        }
        loginInfo.remove(CLIENT_SECRET);
        AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, getScope(req));
        authorizationRequest.setRequestParameters(getSingleValueMap(req));
        authorizationRequest.setApproved(true);
        //must set this to true in order for
        //Authentication.isAuthenticated to return true
        OAuth2Authentication result = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
                null);
        result.setAuthenticated(true);
        return result;
    } catch (AuthenticationException e) {
        throw new BadCredentialsException(e.getMessage(), e);
    } catch (Exception e) {
        logger.debug("Unable to authenticate client: " + clientId, e);
        throw new BadCredentialsException(e.getMessage(), e);
    }
}

From source file:org.cloudfoundry.identity.uaa.authentication.ClientParametersAuthenticationFilter.java

private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo,
        String clientId) {//from w ww. j  a va 2  s  . c  o  m

    String clientSecret = loginInfo.get(CLIENT_SECRET);
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId,
            clientSecret);
    authentication.setDetails(new UaaAuthenticationDetails(req, clientId));
    try {
        Authentication auth = clientAuthenticationManager.authenticate(authentication);
        if (auth == null || !auth.isAuthenticated()) {
            throw new BadCredentialsException("Client Authentication failed.");
        }
        loginInfo.remove(CLIENT_SECRET);
        AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, getScope(req));
        authorizationRequest.setRequestParameters(getSingleValueMap(req));
        authorizationRequest.setApproved(true);
        //must set this to true in order for
        //Authentication.isAuthenticated to return true
        OAuth2Authentication result = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
                null);
        result.setAuthenticated(true);
        return result;
    } catch (AuthenticationException e) {
        throw new BadCredentialsException(e.getMessage(), e);
    } catch (Exception e) {
        logger.debug("Unable to authenticate client: " + clientId, e);
        throw new BadCredentialsException(e.getMessage(), e);
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
    Map<String, Object> claims = getClaimsForToken(accessToken);

    // Check token expiry
    Integer expiration = (Integer) claims.get(EXP);
    if (expiration != null && new Date(expiration * 1000l).before(new Date())) {
        throw new InvalidTokenException("Invalid access token (expired): " + accessToken + " expired at "
                + new Date(expiration * 1000l));
    }/*  ww  w.  jav  a2  s. c o m*/

    // Check client ID is valid
    validateClient((String) claims.get(CLIENT_ID));
    validateClient((String) claims.get(CID));

    @SuppressWarnings("unchecked")
    ArrayList<String> scopes = (ArrayList<String>) claims.get(SCOPE);

    AuthorizationRequest authorizationRequest = new AuthorizationRequest((String) claims.get(CLIENT_ID),
            scopes);

    ArrayList<String> rids = (ArrayList<String>) claims.get(AUD);
    //TODO - Fix null resource IDs for a client_credentials request to /oauth/token
    Set<String> resourceIds = Collections
            .unmodifiableSet(rids == null ? new HashSet<String>() : new HashSet<>(rids));
    authorizationRequest.setResourceIds(resourceIds);

    authorizationRequest.setApproved(true);

    Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
            StringUtils.collectionToCommaDelimitedString(defaultUserAuthorities));
    if (claims.containsKey("authorities")) {
        Object authoritiesFromClaims = claims.get("authorities");
        if (authoritiesFromClaims instanceof String) {
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) authoritiesFromClaims);
        }
        if (authoritiesFromClaims instanceof Collection) {
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
                    StringUtils.collectionToCommaDelimitedString((Collection<?>) authoritiesFromClaims));
        }
    }

    Authentication userAuthentication = null;
    // Is this a user token?
    if (claims.containsKey(EMAIL)) {
        UaaUser user = new UaaUser((String) claims.get(USER_ID), (String) claims.get(USER_NAME), null,
                (String) claims.get(EMAIL), UaaAuthority.USER_AUTHORITIES, null, null, null, null, null, null,
                false);

        UaaPrincipal principal = new UaaPrincipal(user);
        userAuthentication = new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES, null);
    } else {
        authorizationRequest.setAuthorities(authorities);
    }

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);
    authentication.setAuthenticated(true);
    return authentication;
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
    if (StringUtils.isEmpty(accessToken)) {
        throw new InvalidTokenException(
                "Invalid access token value, must be at least 30 characters:" + accessToken);
    }// w  ww. j ava  2 s. com

    TokenValidation tokenValidation = validateToken(accessToken);
    Map<String, Object> claims = tokenValidation.getClaims();
    accessToken = tokenValidation.getJwt().getEncoded();

    // Check token expiry
    Integer expiration = (Integer) claims.get(EXP);
    if (expiration != null && new Date(expiration * 1000l).before(new Date())) {
        throw new InvalidTokenException("Invalid access token (expired): " + accessToken + " expired at "
                + new Date(expiration * 1000l));
    }

    @SuppressWarnings("unchecked")
    ArrayList<String> scopes = (ArrayList<String>) claims.get(SCOPE);

    AuthorizationRequest authorizationRequest = new AuthorizationRequest((String) claims.get(CLIENT_ID),
            scopes);

    ArrayList<String> rids = (ArrayList<String>) claims.get(AUD);
    //TODO - Fix null resource IDs for a client_credentials request to /oauth/token
    Set<String> resourceIds = Collections
            .unmodifiableSet(rids == null ? new HashSet<String>() : new HashSet<>(rids));
    authorizationRequest.setResourceIds(resourceIds);

    authorizationRequest.setApproved(true);

    Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
            StringUtils.collectionToCommaDelimitedString(defaultUserAuthorities));
    if (claims.containsKey("authorities")) {
        Object authoritiesFromClaims = claims.get("authorities");
        if (authoritiesFromClaims instanceof String) {
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) authoritiesFromClaims);
        }
        if (authoritiesFromClaims instanceof Collection) {
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
                    StringUtils.collectionToCommaDelimitedString((Collection<?>) authoritiesFromClaims));
        }
    }

    Authentication userAuthentication = null;
    // Is this a user token - minimum info is user_id
    if (claims.containsKey(USER_ID)) {
        UaaUser user = userDatabase.retrieveUserById((String) claims.get(USER_ID));
        UaaPrincipal principal = new UaaPrincipal(user);
        userAuthentication = new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES, null);
    } else {
        authorizationRequest.setAuthorities(authorities);
    }

    OAuth2Authentication authentication = new UaaOauth2Authentication(accessToken,
            IdentityZoneHolder.get().getId(), authorizationRequest.createOAuth2Request(), userAuthentication);
    authentication.setAuthenticated(true);
    return authentication;
}