Example usage for org.springframework.security.oauth2.common.util OAuth2Utils formatParameterList

List of usage examples for org.springframework.security.oauth2.common.util OAuth2Utils formatParameterList

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.util OAuth2Utils formatParameterList.

Prototype

public static String formatParameterList(Collection<String> value) 

Source Link

Document

Formats a set of string values into a format appropriate for sending as a single-valued form value.

Usage

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

@Override
public String extractKey(OAuth2Authentication authentication) {
    Map<String, Object> values = new LinkedHashMap<String, Object>();
    AuthorizationRequest authorizationRequest = authentication.getAuthorizationRequest();
    if (!authentication.isClientOnly()) {
        values.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication()));
    }//from  www. j  av a2  s  .c  o  m
    ClientDetails client = clientDetailsService.loadClientByClientId(authorizationRequest.getClientId());
    values.put(CLIENT_ID, client.getClientId());
    if (authorizationRequest.getScope() != null) {
        values.put(SCOPE, OAuth2Utils.formatParameterList(authorizationRequest.getScope()));
    }
    Integer validity = client.getAccessTokenValiditySeconds();
    if (validity != null) {
        values.put(ACCESS_TOKEN_VALIDITY, validity);
    }
    validity = client.getRefreshTokenValiditySeconds();
    if (validity != null && client.getAuthorizedGrantTypes().contains("refresh_token")) {
        values.put(REFRESH_TOKEN_VALIDITY, validity);
    }
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).");
    }

    try {
        byte[] bytes = digest.digest(values.toString().getBytes("UTF-8"));
        return String.format("%032x", new BigInteger(1, bytes));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("UTF-8 encoding not available.  Fatal (should be in the JDK).");
    }
}

From source file:com.example.ProxyAuthorizationServerTokenServices.java

private MultiValueMap<String, String> createForm(String refreshToken, TokenRequest tokenRequest) {
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.set(OAuth2Utils.GRANT_TYPE, "refresh_token");
    form.set("refresh_token", refreshToken);
    if (!tokenRequest.getScope().isEmpty()) {
        form.set(OAuth2Utils.SCOPE, OAuth2Utils.formatParameterList(tokenRequest.getScope()));
    }/*w w  w.j av  a2 s .c o m*/
    return form;
}

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

/**
 * Create an authorization request applying various UAA rules to the authorizationParameters and the registered
 * client details.//  w  ww .jav  a 2s .  c  o  m
 * <ul>
 * <li>For client_credentials grants, the default scopes are the client's granted authorities</li>
 * <li>For other grant types the default scopes are the registered scopes in the client details</li>
 * <li>Only scopes in those lists are valid, otherwise there is an exception</li>
 * <li>If the scopes contain separators then resource ids are extracted as the scope value up to the last index of
 * the separator</li>
 * <li>Some scopes can be hard-wired to resource ids (like the open id connect values), in which case the separator
 * is ignored</li>
 * </ul>
 *
 * @see org.springframework.security.oauth2.provider.AuthorizationRequestFactory#createAuthorizationRequest(java.util.Map,
 * java.lang.String, java.lang.String, java.util.Set)
 */
@Override
public AuthorizationRequest createAuthorizationRequest(Map<String, String> authorizationParameters) {

    String clientId = authorizationParameters.get("client_id");
    BaseClientDetails clientDetails = new BaseClientDetails(
            clientDetailsService.loadClientByClientId(clientId));

    Set<String> scopes = OAuth2Utils.parseParameterList(authorizationParameters.get("scope"));
    String grantType = authorizationParameters.get("grant_type");
    if ((scopes == null || scopes.isEmpty())) {
        if ("client_credentials".equals(grantType)) {
            // The client authorities should be a list of scopes
            scopes = AuthorityUtils.authorityListToSet(clientDetails.getAuthorities());
        } else {
            // The default for a user token is the scopes registered with the client
            scopes = clientDetails.getScope();
        }
    }

    Set<String> scopesFromExternalAuthorities = null;
    if (!"client_credentials".equals(grantType) && securityContextAccessor.isUser()) {
        scopes = checkUserScopes(scopes, securityContextAccessor.getAuthorities(), clientDetails);

        // TODO: will the grantType ever contain client_credentials or authorization_code
        // External Authorities are things like LDAP groups that will be mapped to Oauth scopes
        // Add those scopes to the request. These scopes will not be validated against the scopes
        // registered to a client.
        // These scopes also do not need approval. The fact that they are already in an external
        // group communicates user approval. Denying approval does not mean much
        scopesFromExternalAuthorities = findScopesFromAuthorities(authorizationParameters.get("authorities"));
    }

    Set<String> resourceIds = getResourceIds(clientDetails, scopes);
    clientDetails.setResourceIds(resourceIds);
    DefaultAuthorizationRequest request = new DefaultAuthorizationRequest(authorizationParameters);
    if (!scopes.isEmpty()) {
        request.setScope(scopes);
    }
    if (scopesFromExternalAuthorities != null) {
        Map<String, String> existingAuthorizationParameters = new LinkedHashMap<String, String>();
        existingAuthorizationParameters.putAll(request.getAuthorizationParameters());
        existingAuthorizationParameters.put("external_scopes",
                OAuth2Utils.formatParameterList(scopesFromExternalAuthorities));
        request.setAuthorizationParameters(existingAuthorizationParameters);
    }

    request.addClientDetails(clientDetails);

    return request;
}

From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) {

    Map<String, Object> vars = new LinkedHashMap<>();
    Map<String, String> keys = new HashMap<>();

    if (isNull(accessToken)) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }//from www.  j av  a 2  s . co  m

    vars.put("access_token", accessToken.getValue());
    vars.put("token_type", accessToken.getTokenType());
    String state = authorizationRequest.getState();

    if (nonNull(state)) {
        vars.put("state", state);
    }

    Date expiration = accessToken.getExpiration();
    if (nonNull(expiration)) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        vars.put("expires_in", expires_in);
    }

    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (isNull(originalScope)
            || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        vars.put("scope", OAuth2Utils.formatParameterList(accessToken.getScope()));
    }

    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (nonNull(value)) {
            keys.put("extra_" + key, key);
            vars.put("extra_" + key, value);
        }
    }
    // Do not include the refresh token (even if there is one)
    return append(authorizationRequest.getRedirectUri(), vars, keys, true);
}

From source file:org.mitre.oauth2.introspectingfilter.IntrospectingTokenService.java

private OAuth2Request createStoredRequest(final JsonObject token) {
    String clientId = token.get("client_id").getAsString();
    Set<String> scopes = new HashSet<>();
    if (token.has("scope")) {
        scopes.addAll(OAuth2Utils.parseParameterList(token.get("scope").getAsString()));
    }//from   w  w w  .  ja  v  a2  s  .c  o  m
    Map<String, String> parameters = new HashMap<>();
    parameters.put("client_id", clientId);
    parameters.put("scope", OAuth2Utils.formatParameterList(scopes));
    OAuth2Request storedRequest = new OAuth2Request(parameters, clientId, null, true, scopes, null, null, null,
            null);
    return storedRequest;
}

From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java

private MultiValueMap<String, String> getParametersForAuthorizeRequest(
        AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {

    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("response_type", "code");
    form.set("client_id", resource.getClientId());

    if (request.get("scope") != null) {
        form.set("scope", request.getFirst("scope"));
    } else {/*from   w  ww  .j  a v a  2  s  . c o  m*/
        form.set("scope", OAuth2Utils.formatParameterList(resource.getScope()));
    }

    // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to
    // resource.getRedirectUri()
    String redirectUri = resource.getPreEstablishedRedirectUri();

    Object preservedState = request.getPreservedState();
    if (redirectUri == null && preservedState != null) {
        // no pre-established redirect uri: use the preserved state
        // TODO: treat redirect URI as a special kind of state (this is a historical mini hack)
        redirectUri = String.valueOf(preservedState);
    } else {
        redirectUri = request.getCurrentUri();
    }

    String stateKey = request.getStateKey();
    if (stateKey != null) {
        form.set("state", stateKey);
        if (preservedState == null) {
            throw new InvalidRequestException(
                    "Possible CSRF detected - state parameter was present but no state could be found");
        }
    }

    if (redirectUri != null) {
        form.set("redirect_uri", redirectUri);
    }

    return form;

}

From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java

private MultiValueMap<String, String> getParametersForAuthorizeRequest(GoogleAuthCodeResourceDetails resource,
        AccessTokenRequest request) {/*  ww  w.ja va2  s . com*/

    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.set("response_type", "code");
    form.set("client_id", resource.getClientId());

    if (request.get("scope") != null) {
        form.set("scope", request.getFirst("scope"));
    } else {
        form.set("scope", OAuth2Utils.formatParameterList(resource.getScope()));
    }

    // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to
    // resource.getRedirectUri()
    String redirectUri = resource.getPreEstablishedRedirectUri();

    Object preservedState = request.getPreservedState();
    if (redirectUri == null && preservedState != null) {
        // no pre-established redirect uri: use the preserved state
        // TODO: treat redirect URI as a special kind of state (this is a historical mini hack)
        redirectUri = String.valueOf(preservedState);
    } else {
        redirectUri = request.getCurrentUri();
    }

    String stateKey = request.getStateKey();
    if (stateKey != null) {
        form.set("state", stateKey);
        if (preservedState == null) {
            throw new InvalidRequestException(
                    "Possible CSRF detected - state parameter was present but no state could be found");
        }
    }

    form.set("approval_prompt", resource.getApprovalPrompt());

    if (StringUtils.isEmpty(resource.getLoginHint())) {
        form.set("login_hint", resource.getLoginHint());
    }

    if (redirectUri != null) {
        form.set("redirect_uri", redirectUri);
    }

    return form;

}

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

public String buildRedirectURI(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken,
        Authentication authUser) {/*from w w w . j  av a  2 s .c o  m*/

    String requestedRedirect = authorizationRequest.getRedirectUri();
    if (accessToken == null) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }

    StringBuilder url = new StringBuilder();
    url.append("token_type=").append(encode(accessToken.getTokenType()));

    //only append access token if grant_type is implicit
    //or token is part of the response type
    if (authorizationRequest.getResponseTypes().contains("token")) {
        url.append("&access_token=").append(encode(accessToken.getValue()));
    }

    if (accessToken instanceof CompositeToken
            && authorizationRequest.getResponseTypes().contains(CompositeToken.ID_TOKEN)) {
        url.append("&").append(CompositeToken.ID_TOKEN).append("=")
                .append(encode(((CompositeToken) accessToken).getIdTokenValue()));
    }

    if (authorizationRequest.getResponseTypes().contains("code")) {
        String code = generateCode(authorizationRequest, authUser);
        url.append("&code=").append(encode(code));
    }

    String state = authorizationRequest.getState();
    if (state != null) {
        url.append("&state=").append(encode(state));
    }

    Date expiration = accessToken.getExpiration();
    if (expiration != null) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        url.append("&expires_in=").append(expires_in);
    }

    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (originalScope == null
            || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        url.append("&" + OAuth2Utils.SCOPE + "=")
                .append(encode(OAuth2Utils.formatParameterList(accessToken.getScope())));
    }

    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (value != null) {
            url.append("&" + encode(key) + "=" + encode(value.toString()));
        }
    }

    if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
        HttpHost httpHost = URIUtils.extractHost(URI.create(requestedRedirect));
        String sessionState = openIdSessionStateCalculator.calculate(
                ((UaaPrincipal) authUser.getPrincipal()).getId(), authorizationRequest.getClientId(),
                httpHost.toURI());

        url.append("&session_state=").append(sessionState);
    }

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(requestedRedirect);
    String existingFragment = builder.build(true).getFragment();
    if (StringUtils.hasText(existingFragment)) {
        existingFragment = existingFragment + "&" + url.toString();
    } else {
        existingFragment = url.toString();
    }
    builder.fragment(existingFragment);
    // Do not include the refresh token (even if there is one)
    return builder.build(true).toUriString();
}

From source file:org.orcid.core.oauth.OrcidClientCredentialsChecker.java

private void validateScope(ClientDetails clientDetails, Set<String> scopes) {

    if (clientDetails.isScoped()) {
        Set<String> validScope = clientDetails.getScope();
        if (scopes.isEmpty()) {
            throw new InvalidScopeException("Invalid scope (none)", validScope);
        } else if (!containsAny(validScope, ScopePathType.ORCID_PROFILE_CREATE, ScopePathType.WEBHOOK,
                ScopePathType.PREMIUM_NOTIFICATION, ScopePathType.GROUP_ID_RECORD_READ,
                ScopePathType.GROUP_ID_RECORD_UPDATE) && !scopes.contains(ScopePathType.READ_PUBLIC.value())
                && scopes.size() == 1) {
            throw new InvalidScopeException(
                    "Invalid scope" + (scopes != null && scopes.size() > 1 ? "s: " : ": " + "")
                            + OAuth2Utils.formatParameterList(scopes),
                    validScope);/*from  w  ww  .j a  v a2 s.c  o m*/
        }

        // The Read public does not have to be granted. It's the implied
        // read level. We let this through, regardless
        if (scopes.size() == 1 && scopes.iterator().next().equals(ScopePathType.READ_PUBLIC.value())) {
            return;
        }

        for (String scope : scopes) {
            if (!validScope.contains(scope)) {
                throw new InvalidScopeException("Invalid scope: " + scope, validScope);
            }
        }
    }

}

From source file:org.orcid.core.oauth.service.OrcidTokenStoreServiceImpl.java

private OrcidOauth2TokenDetail populatePropertiesFromTokenAndAuthentication(OAuth2AccessToken token,
        OAuth2Authentication authentication, OrcidOauth2TokenDetail detail) {
    OAuth2Request authorizationRequest = authentication.getOAuth2Request();
    if (detail == null) {
        detail = new OrcidOauth2TokenDetail();
    }/*from w w  w  .ja  v a  2s  .com*/
    String clientId = authorizationRequest.getClientId();
    String authKey = KEY_GENERATOR.extractKey(authentication);
    detail.setAuthenticationKey(authKey);
    detail.setClientDetailsId(clientId);

    OAuth2RefreshToken refreshToken = token.getRefreshToken();
    if (refreshToken != null && StringUtils.isNotBlank(refreshToken.getValue())) {
        if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
            // Override the refresh token expiration from the client
            // details, and make it the same as the token itself
            detail.setRefreshTokenExpiration(token.getExpiration());
        }
        detail.setRefreshTokenValue(refreshToken.getValue());
    }
    if (!authentication.isClientOnly()) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof ProfileEntity) {
            ProfileEntity profileEntity = (ProfileEntity) authentication.getPrincipal();
            profileEntity = profileEntityCacheManager.retrieve(profileEntity.getId());
            detail.setProfile(profileEntity);
        }
    }

    detail.setTokenValue(token.getValue());
    detail.setTokenType(token.getTokenType());
    detail.setTokenExpiration(token.getExpiration());
    detail.setApproved(authorizationRequest.isApproved());
    detail.setRedirectUri(authorizationRequest.getRedirectUri());

    Set<String> resourceIds = authorizationRequest.getResourceIds();
    if (resourceIds == null || resourceIds.isEmpty()) {
        ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
        resourceIds = clientDetails.getResourceIds();
    }

    detail.setResourceId(OAuth2Utils.formatParameterList(resourceIds));
    detail.setResponseType(OAuth2Utils.formatParameterList(authorizationRequest.getResponseTypes()));
    detail.setScope(OAuth2Utils.formatParameterList(authorizationRequest.getScope()));

    Map<String, Object> additionalInfo = token.getAdditionalInformation();
    if (additionalInfo != null) {
        if (additionalInfo.containsKey(OrcidOauth2Constants.TOKEN_VERSION)) {
            String sVersion = String.valueOf(additionalInfo.get(OrcidOauth2Constants.TOKEN_VERSION));
            detail.setVersion(Long.valueOf(sVersion));
        } else {
            // TODO: As of Jan 2015 all tokens will be new tokens, so, we
            // will have to remove the token version code and
            // treat all tokens as new tokens
            detail.setVersion(Long.valueOf(OrcidOauth2Constants.PERSISTENT_TOKEN));
        }

        if (additionalInfo.containsKey(OrcidOauth2Constants.PERSISTENT)) {
            boolean isPersistentKey = (Boolean) additionalInfo.get(OrcidOauth2Constants.PERSISTENT);
            detail.setPersistent(isPersistentKey);
        } else {
            detail.setPersistent(false);
        }
    } else {
        detail.setPersistent(false);
    }

    return detail;
}