Example usage for org.springframework.security.oauth2.provider AuthorizationRequest setApproved

List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest setApproved

Introduction

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

Prototype

public void setApproved(boolean approved) 

Source Link

Usage

From source file:org.smartplatforms.openid.connect.token.SmartTofuUserApprovalHandler.java

/**
 * Check if the user has already stored a positive approval decision for this site; or if the
 * site is whitelisted, approve it automatically.
 * //from ww w  . j av  a2  s.  com
 * Otherwise the user will be directed to the approval page and can make their own decision.
 * 
 * @param authorizationRequest   the incoming authorization request
 * @param userAuthentication   the Principal representing the currently-logged-in user
 * 
 * @return                   the updated AuthorizationRequest
 */
@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    //First, check database to see if the user identified by the userAuthentication has stored an approval decision

    String userId = userAuthentication.getName();
    String clientId = authorizationRequest.getClientId();

    //lookup ApprovedSites by userId and clientId
    boolean alreadyApproved = false;

    // find out if we're supposed to force a prompt on the user or not
    String prompt = (String) authorizationRequest.getExtensions().get(PROMPT);
    List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));
    if (!prompts.contains(PROMPT_SEPARATOR)) {
        // if the prompt parameter is set to "consent" then we can't use approved sites or whitelisted sites
        // otherwise, we need to check them below

        Collection<ApprovedSite> aps = approvedSiteService.getByClientIdAndUserId(clientId, userId);
        for (ApprovedSite ap : aps) {

            if (!ap.isExpired()) {

                // if we find one that fits...
                if (systemScopes.scopesMatch(ap.getAllowedScopes(), authorizationRequest.getScope())) {

                    //We have a match; update the access date on the AP entry and return true.
                    ap.setAccessDate(new Date());
                    approvedSiteService.save(ap);

                    String apId = ap.getId().toString();
                    authorizationRequest.getExtensions().put(APPROVED_SITE, apId);
                    authorizationRequest.setApproved(true);
                    alreadyApproved = true;

                    setAuthTime(authorizationRequest);
                }
            }
        }

        if (!alreadyApproved) {
            WhitelistedSite ws = whitelistedSiteService.getByClientId(clientId);
            if (ws != null
                    && systemScopes.scopesMatch(ws.getAllowedScopes(), authorizationRequest.getScope())) {
                authorizationRequest.setApproved(true);

                setAuthTime(authorizationRequest);
            }
        }
    }

    return authorizationRequest;

}

From source file:com.ge.predix.uaa.token.lib.FastTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException {
    Map<String, Object> claims;
    try {/*from   ww  w.  j  a v  a 2  s .  c om*/
        claims = getTokenClaims(accessToken);
    } catch (IllegalArgumentException e) {
        LOG.error("Malformed Access Token: " + accessToken);
        LOG.error(e);
        throw new InvalidTokenException("Malformed Access Token", e);
    }
    String iss = getIssuerFromClaims(claims);

    verifyIssuer(iss);

    // check if the singerProvider for that issuer has already in the cache
    SignatureVerifier verifier = this.tokenKeys.get(iss);
    if (null == verifier) {
        String tokenKey = getTokenKey(iss);
        verifier = getVerifier(tokenKey);
        this.tokenKeys.put(iss, verifier);
    }

    JwtHelper.decodeAndVerify(accessToken, verifier);
    verifyTimeWindow(claims);

    Assert.state(claims.containsKey("client_id"), "Client id must be present in response from auth server");
    String remoteClientId = (String) claims.get("client_id");

    Set<String> scope = new HashSet<>();
    if (claims.containsKey("scope")) {
        @SuppressWarnings("unchecked")
        Collection<String> values = (Collection<String>) claims.get("scope");
        scope.addAll(values);
    }

    AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope);

    if (claims.containsKey("resource_ids") || claims.containsKey("client_authorities")) {
        Set<String> resourceIds = new HashSet<>();
        if (claims.containsKey("resource_ids")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) claims.get("resource_ids");
            resourceIds.addAll(values);
        }

        Set<GrantedAuthority> clientAuthorities = new HashSet<>();
        if (claims.containsKey("client_authorities")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) claims.get("client_authorities");
            clientAuthorities.addAll(getAuthorities(values));
        }

        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(remoteClientId);
        clientDetails.setResourceIds(resourceIds);
        clientDetails.setAuthorities(clientAuthorities);
        clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
    }

    Map<String, String> requestParameters = new HashMap<>();
    if (isStoreClaims()) {
        for (Map.Entry<String, Object> entry : claims.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof String) {
                requestParameters.put(entry.getKey(), (String) entry.getValue());
            }
        }
    }

    if (claims.containsKey(Claims.ADDITIONAL_AZ_ATTR)) {
        try {
            requestParameters.put(Claims.ADDITIONAL_AZ_ATTR,
                    JsonUtils.writeValueAsString(claims.get(Claims.ADDITIONAL_AZ_ATTR)));
        } catch (JsonUtils.JsonUtilException e) {
            throw new IllegalStateException("Cannot convert access token to JSON", e);
        }
    }
    clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters));

    Authentication userAuthentication = getUserAuthentication(claims, scope);

    clientAuthentication.setApproved(true);
    return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication);
}

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

@RequestMapping(value = "/oauth/authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model,
        SessionStatus sessionStatus, Principal principal) {

    if (!(principal instanceof Authentication)) {
        sessionStatus.setComplete();/*  w ww . j  av  a  2 s . c  o m*/
        throw new InsufficientAuthenticationException(
                "User must be authenticated with Spring Security before authorizing an access token.");
    }

    AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get(AUTHORIZATION_REQUEST);

    if (authorizationRequest == null) {
        sessionStatus.setComplete();
        throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
    }

    // Check to ensure the Authorization Request was not modified during the user approval step
    @SuppressWarnings("unchecked")
    Map<String, Object> originalAuthorizationRequest = (Map<String, Object>) model
            .get(ORIGINAL_AUTHORIZATION_REQUEST);
    if (isAuthorizationRequestModified(authorizationRequest, originalAuthorizationRequest)) {
        logger.warn("The requested scopes are invalid");
        throw new InvalidRequestException("Changes were detected from the original authorization request.");
    }

    for (String approvalParameter : approvalParameters.keySet()) {
        if (approvalParameter.startsWith(SCOPE_PREFIX)) {
            String scope = approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length());
            Set<String> originalScopes = (Set<String>) originalAuthorizationRequest.get("scope");
            if (!originalScopes.contains(scope)) {
                sessionStatus.setComplete();

                logger.warn("The requested scopes are invalid");
                return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, new InvalidScopeException(
                        "The requested scopes are invalid. Please use valid scope names in the request."),
                        false), false, true, false);
            }
        }
    }

    try {
        Set<String> responseTypes = authorizationRequest.getResponseTypes();
        String grantType = deriveGrantTypeFromResponseType(responseTypes);

        authorizationRequest.setApprovalParameters(approvalParameters);
        authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest,
                (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        if (authorizationRequest.getRedirectUri() == null) {
            sessionStatus.setComplete();
            throw new InvalidRequestException("Cannot approve request when no redirect URI is provided.");
        }

        if (!authorizationRequest.isApproved()) {
            return new RedirectView(getUnsuccessfulRedirect(authorizationRequest,
                    new UserDeniedAuthorizationException("User denied access"),
                    responseTypes.contains("token")), false, true, false);
        }

        if (responseTypes.contains("token") || responseTypes.contains("id_token")) {
            return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal, grantType)
                    .getView();
        }

        return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal);
    } finally {
        sessionStatus.setComplete();
    }

}

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

@RequestMapping(value = "/oauth/authorize")
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
        SessionStatus sessionStatus, Principal principal, HttpServletRequest request) {

    ClientDetails client;/*from  ww  w.  j  a  v a 2  s . co  m*/
    String clientId;
    try {
        clientId = parameters.get("client_id");
        client = getClientServiceExtention().loadClientByClientId(clientId, IdentityZoneHolder.get().getId());
    } catch (NoSuchClientException x) {
        throw new InvalidClientException(x.getMessage());
    }

    // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
    // query off of the authorization request instead of referring back to the parameters map. The contents of the
    // parameters map will be stored without change in the AuthorizationRequest object once it is created.
    AuthorizationRequest authorizationRequest;
    try {
        authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);
    } catch (DisallowedIdpException x) {
        return switchIdp(model, client, clientId, request);
    }

    Set<String> responseTypes = authorizationRequest.getResponseTypes();
    String grantType = deriveGrantTypeFromResponseType(responseTypes);

    if (!supported_response_types.containsAll(responseTypes)) {
        throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
    }

    if (authorizationRequest.getClientId() == null) {
        throw new InvalidClientException("A client id must be provided");
    }

    String resolvedRedirect = "";
    try {
        String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
        try {
            resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        } catch (RedirectMismatchException rme) {
            throw new RedirectMismatchException(
                    "Invalid redirect " + redirectUriParameter + " did not match one of the registered values");
        }
        if (!StringUtils.hasText(resolvedRedirect)) {
            throw new RedirectMismatchException(
                    "A redirectUri must be either supplied or preconfigured in the ClientDetails");
        }

        boolean isAuthenticated = (principal instanceof Authentication)
                && ((Authentication) principal).isAuthenticated();

        if (!isAuthenticated) {
            throw new InsufficientAuthenticationException(
                    "User must be authenticated with Spring Security before authorization can be completed.");
        }

        if (!(responseTypes.size() > 0)) {
            return new ModelAndView(new RedirectView(
                    addQueryParameter(addQueryParameter(resolvedRedirect, "error", "invalid_request"),
                            "error_description", "Missing response_type in authorization request")));
        }

        authorizationRequest.setRedirectUri(resolvedRedirect);
        // We intentionally only validate the parameters requested by the client (ignoring any data that may have
        // been added to the request by the manager).
        oauth2RequestValidator.validateScope(authorizationRequest, client);

        // Some systems may allow for approval decisions to be remembered or approved by default. Check for
        // such logic here, and set the approved flag on the authorization request accordingly.
        authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,
                (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        // Validation is all done, so we can check for auto approval...
        if (authorizationRequest.isApproved()) {
            if (responseTypes.contains("token") || responseTypes.contains("id_token")) {
                return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal,
                        grantType);
            }
            if (responseTypes.contains("code")) {
                return new ModelAndView(
                        getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal));
            }
        }

        if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
            return new ModelAndView(
                    new RedirectView(addFragmentComponent(resolvedRedirect, "error=interaction_required")));
        } else {
            // Place auth request into the model so that it is stored in the session
            // for approveOrDeny to use. That way we make sure that auth request comes from the session,
            // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
            model.put(AUTHORIZATION_REQUEST, authorizationRequest);
            model.put("original_uri", UrlUtils.buildFullRequestUrl(request));
            model.put(ORIGINAL_AUTHORIZATION_REQUEST, unmodifiableMap(authorizationRequest));

            return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);
        }
    } catch (RedirectMismatchException e) {
        sessionStatus.setComplete();
        throw e;
    } catch (Exception e) {
        sessionStatus.setComplete();
        logger.debug("Unable to handle /oauth/authorize, internal error", e);
        if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
            return new ModelAndView(
                    new RedirectView(addFragmentComponent(resolvedRedirect, "error=internal_server_error")));
        }

        throw e;
    }

}

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

private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo,
        String clientId) {//  w w w .  ja va 2  s . co 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.BackwardsCompatibleTokenEndpointAuthenticationFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {/*from ww w  .  j a v  a  2s .c om*/
        Authentication userAuthentication = extractCredentials(request, response);

        if (userAuthentication != null) {
            Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication();
            if (clientAuth == null) {
                throw new BadCredentialsException(
                        "No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter.");
            }

            Map<String, String> map = getSingleValueMap(request);
            map.put(OAuth2Utils.CLIENT_ID, clientAuth.getName());

            SecurityContextHolder.getContext().setAuthentication(userAuthentication);
            AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map);

            //authorizationRequest.setScope(getScope(request));
            if (clientAuth.isAuthenticated()) {
                // Ensure the OAuth2Authentication is authenticated
                authorizationRequest.setApproved(true);
            }

            OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest);

            SecurityContextHolder.getContext()
                    .setAuthentication(new OAuth2Authentication(storedOAuth2Request, userAuthentication));

            onSuccessfulAuthentication(request, response, userAuthentication);
        }
    } catch (UnauthorizedClientException failed) {
        //happens when all went well, but the client is not authorized for the identity provider
        UnapprovedClientAuthenticationException ex = new UnapprovedClientAuthenticationException(
                failed.getMessage(), failed);
        SecurityContextHolder.clearContext();
        logger.debug("Authentication request for failed: " + failed);
        onUnsuccessfulAuthentication(request, response, ex);
        authenticationEntryPoint.commence(request, response, ex);
        return;
    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();
        logger.debug("Authentication request for failed: " + failed);
        onUnsuccessfulAuthentication(request, response, failed);
        authenticationEntryPoint.commence(request, response, failed);
        return;
    } catch (InvalidScopeException ex) {
        String message = ex.getMessage();
        response.sendError(UNAUTHORIZED.value(), message);
        return;
    }

    chain.doFilter(request, response);
}

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

private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo,
        String clientId) {/*  ww w.  ja  v a  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.RemoteTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("token", accessToken);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
    Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers);

    if (map.containsKey("error")) {
        logger.debug("check_token returned error: " + map.get("error"));
        throw new InvalidTokenException(accessToken);
    }//from   w w w. ja v  a 2  s .c o  m

    Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
    String remoteClientId = (String) map.get("client_id");

    Set<String> scope = new HashSet<String>();
    if (map.containsKey("scope")) {
        @SuppressWarnings("unchecked")
        Collection<String> values = (Collection<String>) map.get("scope");
        scope.addAll(values);
    }
    AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope);

    if (map.containsKey("resource_ids") || map.containsKey("client_authorities")) {
        Set<String> resourceIds = new HashSet<String>();
        if (map.containsKey("resource_ids")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("resource_ids");
            resourceIds.addAll(values);
        }
        Set<GrantedAuthority> clientAuthorities = new HashSet<GrantedAuthority>();
        if (map.containsKey("client_authorities")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("client_authorities");
            clientAuthorities.addAll(getAuthorities(values));
        }
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(remoteClientId);
        clientDetails.setResourceIds(resourceIds);
        clientDetails.setAuthorities(clientAuthorities);
        clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
    }
    Map<String, String> requestParameters = new HashMap<>();
    if (isStoreClaims()) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof String) {
                requestParameters.put(entry.getKey(), (String) entry.getValue());
            }
        }
    }

    if (map.containsKey(ClaimConstants.ADDITIONAL_AZ_ATTR)) {
        try {
            requestParameters.put(ClaimConstants.ADDITIONAL_AZ_ATTR,
                    JsonUtils.writeValueAsString(map.get(ClaimConstants.ADDITIONAL_AZ_ATTR)));
        } catch (JsonUtils.JsonUtilException e) {
            throw new IllegalStateException("Cannot convert access token to JSON", e);
        }
    }
    clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters));

    Authentication userAuthentication = getUserAuthentication(map, scope);

    clientAuthentication.setApproved(true);
    return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication);
}

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));
    }// w ww  .ja v a 2  s.c  om

    // 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  av a 2 s.c  o m*/

    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;
}