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

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

Introduction

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

Prototype

String SCOPE

To view the source code for org.springframework.security.oauth2.common.util OAuth2Utils SCOPE.

Click Source Link

Document

Constant to use while parsing and formatting parameter maps for OAuth2 requests

Usage

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()));
    }/*from ww w.j a v a  2 s . c o  m*/
    return form;
}

From source file:org.mitre.openid.connect.ConnectOAuth2RequestFactory.java

@Override
public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) {

    AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String>emptyMap(),
            inputParams.get(OAuth2Utils.CLIENT_ID),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null, null, false,
            inputParams.get(OAuth2Utils.STATE), inputParams.get(OAuth2Utils.REDIRECT_URI),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE)));

    //Add extension parameters to the 'extensions' map

    if (inputParams.containsKey("prompt")) {
        request.getExtensions().put("prompt", inputParams.get("prompt"));
    }//from w  w  w .ja v  a2s  . c  o m
    if (inputParams.containsKey("nonce")) {
        request.getExtensions().put("nonce", inputParams.get("nonce"));
    }

    if (inputParams.containsKey("claims")) {
        JsonObject claimsRequest = parseClaimRequest(inputParams.get("claims"));
        if (claimsRequest != null) {
            request.getExtensions().put("claims", claimsRequest.toString());
        }
    }

    if (inputParams.containsKey("request")) {
        request.getExtensions().put("request", inputParams.get("request"));
        processRequestObject(inputParams.get("request"), request);
    }

    if ((request.getScope() == null || request.getScope().isEmpty())) {
        if (request.getClientId() != null) {
            ClientDetails client = clientDetailsService.loadClientByClientId(request.getClientId());
            Set<String> clientScopes = client.getScope();
            request.setScope(clientScopes);
        }
    }

    return request;
}

From source file:org.mitre.openid.connect.request.ConnectOAuth2RequestFactory.java

@Override
public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) {

    AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String>emptyMap(),
            inputParams.get(OAuth2Utils.CLIENT_ID),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null, null, false,
            inputParams.get(OAuth2Utils.STATE), inputParams.get(OAuth2Utils.REDIRECT_URI),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE)));

    //Add extension parameters to the 'extensions' map

    if (inputParams.containsKey(PROMPT)) {
        request.getExtensions().put(PROMPT, inputParams.get(PROMPT));
    }//  w ww .ja  va2 s  . co  m
    if (inputParams.containsKey(NONCE)) {
        request.getExtensions().put(NONCE, inputParams.get(NONCE));
    }

    if (inputParams.containsKey(CLAIMS)) {
        JsonObject claimsRequest = parseClaimRequest(inputParams.get(CLAIMS));
        if (claimsRequest != null) {
            request.getExtensions().put(CLAIMS, claimsRequest.toString());
        }
    }

    if (inputParams.containsKey(MAX_AGE)) {
        request.getExtensions().put(MAX_AGE, inputParams.get(MAX_AGE));
    }

    if (inputParams.containsKey(LOGIN_HINT)) {
        request.getExtensions().put(LOGIN_HINT, inputParams.get(LOGIN_HINT));
    }

    if (inputParams.containsKey(AUD)) {
        request.getExtensions().put(AUD, inputParams.get(AUD));
    }

    if (inputParams.containsKey(REQUEST)) {
        request.getExtensions().put(REQUEST, inputParams.get(REQUEST));
        processRequestObject(inputParams.get(REQUEST), request);
    }

    if (request.getClientId() != null) {
        try {
            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if ((request.getScope() == null || request.getScope().isEmpty())) {
                Set<String> clientScopes = client.getScope();
                request.setScope(clientScopes);
            }

            if (request.getExtensions().get(MAX_AGE) == null && client.getDefaultMaxAge() != null) {
                request.getExtensions().put(MAX_AGE, client.getDefaultMaxAge().toString());
            }
        } catch (OAuth2Exception e) {
            logger.error("Caught OAuth2 exception trying to test client scopes and max age:", e);
        }
    }

    return request;
}

From source file:com.monkeyk.sos.web.controller.OAuthRestController.java

@RequestMapping(value = "/oauth2/rest_token", method = RequestMethod.POST)
@ResponseBody//from ww  w  .java 2 s  .  co m
public OAuth2AccessToken postAccessToken(@RequestBody Map<String, String> parameters) {

    String clientId = getClientId(parameters);
    ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);

    TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);

    if (clientId != null && !"".equals(clientId)) {
        // Only validate the client details if a client authenticated during this
        // request.
        if (!clientId.equals(tokenRequest.getClientId())) {
            // double check to make sure that the client ID in the token request is the same as that in the
            // authenticated client
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }
    }

    if (authenticatedClient != null) {
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
    }

    final String grantType = tokenRequest.getGrantType();
    if (!StringUtils.hasText(grantType)) {
        throw new InvalidRequestException("Missing grant type");
    }
    if ("implicit".equals(grantType)) {
        throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
    }

    if (isAuthCodeRequest(parameters)) {
        // The scope was requested or determined during the authorization step
        if (!tokenRequest.getScope().isEmpty()) {
            LOG.debug("Clearing scope of incoming token request");
            tokenRequest.setScope(Collections.<String>emptySet());
        }
    }

    if (isRefreshTokenRequest(parameters)) {
        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
    }

    OAuth2AccessToken token = getTokenGranter(grantType).grant(grantType, tokenRequest);
    if (token == null) {
        throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType);
    }

    return token;

}

From source file:com.hundsun.sso.controller.OAuthRestController.java

@RequestMapping(value = "/oauth/rest_token", method = RequestMethod.POST)
@ResponseBody//ww w . ja va2s  .  c  o  m
public OAuth2AccessToken postAccessToken(@RequestBody Map<String, String> parameters) {

    String clientId = getClientId(parameters);
    ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);

    TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);

    if (clientId != null && !"".equals(clientId)) {
        // Only validate the client details if a client authenticated during this
        // request.
        if (!clientId.equals(tokenRequest.getClientId())) {
            // double check to make sure that the client ID in the token request is the same as that in the
            // authenticated client
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }
    }

    if (authenticatedClient != null) {
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
    }

    final String grantType = tokenRequest.getGrantType();
    if (!StringUtils.hasText(grantType)) {
        throw new InvalidRequestException("Missing grant type");
    }
    if ("implicit".equals(grantType)) {
        throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
    }

    if (isAuthCodeRequest(parameters)) {
        // The scope was requested or determined during the authorization step
        if (!tokenRequest.getScope().isEmpty()) {
            LOG.debug("Clearing scope of incoming token request");
            tokenRequest.setScope(Collections.<String>emptySet());
        }
    }

    if (isRefreshTokenRequest(parameters)) {
        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
    }

    OAuth2AccessToken token = getTokenGranter(grantType).grant(grantType, tokenRequest);
    if (token == null) {
        throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType);
    }

    return token;

}

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

@Override
protected void configure() {
    setControllerPath("oauth");

    post("token", (req, resp) -> {
        Authentication principal = basicAuthenticator.authenticate(req);

        String clientId = getClientId(principal);
        ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);

        Map<String, String> parameters = MapUtils.createOneDimMap(req.getQueryParams());
        TokenRequest tokenRequest = requestFactory.createTokenRequest(parameters, authenticatedClient);

        // Only validate the client details if a client authenticated during this request.
        if (!isEmpty(clientId) && !clientId.equals(tokenRequest.getClientId())) {
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }/* w  w w .j  a va  2s .c  o  m*/

        if (nonNull(authenticatedClient)) {
            requestValidator.validateScope(tokenRequest, authenticatedClient);
        }

        if (!isEmpty(tokenRequest.getGrantType())) {
            throw new InvalidRequestException("Missing grant type");
        }

        if (tokenRequest.getGrantType().equals("implicit")) {
            throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
        }

        // The scope was requested or determined during the authorization step
        if (isAuthCodeRequest(parameters) && nonEmpty(tokenRequest.getScope())) {
            tokenRequest.setScope(emptySet());
        }

        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        if (isRefreshTokenRequest(parameters)) {
            tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
        }

        OAuth2AccessToken token = tokenGranter.grant(tokenRequest.getGrantType(), tokenRequest);
        if (isNull(token)) {
            throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
        }

        createResponse(resp, token);

    }, Resp(OAuth2AccessToken.class)).produces(JSON);
}

From source file:com.orcid.api.common.server.delegator.impl.OrcidClientCredentialEndPointDelegatorImpl.java

protected OAuth2AccessToken generateToken(Authentication client, Set<String> scopes, String code,
        String redirectUri, String grantType, String refreshToken, String state) {
    String clientId = client.getName();
    Map<String, String> authorizationParameters = new HashMap<String, String>();

    if (scopes != null) {
        String scopesString = StringUtils.join(scopes, ' ');
        authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
    }/*www  .j ava 2  s  .co  m*/

    authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
    if (code != null) {
        authorizationParameters.put("code", code);
        OrcidOauth2AuthoriziationCodeDetail authorizationCodeEntity = orcidOauth2AuthoriziationCodeDetailDao
                .find(code);

        if (authorizationCodeEntity != null) {
            if (orcidOauth2AuthoriziationCodeDetailDao.isPersistentToken(code)) {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "true");
            } else {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
            }

            if (!authorizationParameters.containsKey(OAuth2Utils.SCOPE)
                    || PojoUtil.isEmpty(authorizationParameters.get(OAuth2Utils.SCOPE))) {
                String scopesString = StringUtils.join(authorizationCodeEntity.getScopes(), ' ');
                authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
            }
        } else {
            authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
        }
    }
    if (redirectUri != null) {
        authorizationParameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
    }
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory()
            .createAuthorizationRequest(authorizationParameters);

    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, grantType);

    OAuth2AccessToken token = getTokenGranter().grant(grantType, tokenRequest);
    Object params[] = { grantType };
    if (token == null) {
        LOGGER.info(
                "Unsupported grant type for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}",
                new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
        throw new UnsupportedGrantTypeException(
                localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    LOGGER.info(
            "OAuth2 access token granted: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}, token={}",
            new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri, token });

    return token;
}

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");
    }/*  w w w.  jav  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.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

Map<String, Object> unmodifiableMap(AuthorizationRequest authorizationRequest) {
    Map<String, Object> authorizationRequestMap = new HashMap<>();

    authorizationRequestMap.put(OAuth2Utils.CLIENT_ID, authorizationRequest.getClientId());
    authorizationRequestMap.put(OAuth2Utils.STATE, authorizationRequest.getState());
    authorizationRequestMap.put(OAuth2Utils.REDIRECT_URI, authorizationRequest.getRedirectUri());

    if (authorizationRequest.getResponseTypes() != null) {
        authorizationRequestMap.put(OAuth2Utils.RESPONSE_TYPE,
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getResponseTypes())));
    }/*from w ww .j  av  a  2 s . c om*/
    if (authorizationRequest.getScope() != null) {
        authorizationRequestMap.put(OAuth2Utils.SCOPE,
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getScope())));
    }

    authorizationRequestMap.put("approved", authorizationRequest.isApproved());

    if (authorizationRequest.getResourceIds() != null) {
        authorizationRequestMap.put("resourceIds",
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getResourceIds())));
    }
    if (authorizationRequest.getAuthorities() != null) {
        authorizationRequestMap.put("authorities", Collections
                .unmodifiableSet(new HashSet<GrantedAuthority>(authorizationRequest.getAuthorities())));
    }

    return authorizationRequestMap;
}

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

private boolean isAuthorizationRequestModified(AuthorizationRequest authorizationRequest,
        Map<String, Object> originalAuthorizationRequest) {
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getClientId(),
            originalAuthorizationRequest.get(OAuth2Utils.CLIENT_ID))) {
        return true;
    }//from   w  w  w . j a v a 2 s.co m
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getState(),
            originalAuthorizationRequest.get(OAuth2Utils.STATE))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getRedirectUri(),
            originalAuthorizationRequest.get(OAuth2Utils.REDIRECT_URI))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getResponseTypes(),
            originalAuthorizationRequest.get(OAuth2Utils.RESPONSE_TYPE))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.isApproved(),
            originalAuthorizationRequest.get("approved"))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getResourceIds(),
            originalAuthorizationRequest.get("resourceIds"))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getAuthorities(),
            originalAuthorizationRequest.get("authorities"))) {
        return true;
    }

    return !ObjectUtils.nullSafeEquals(authorizationRequest.getScope(),
            originalAuthorizationRequest.get(OAuth2Utils.SCOPE));
}