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

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

Introduction

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

Prototype

public static Set<String> parseParameterList(String values) 

Source Link

Document

Parses a string parameter value into a set of strings.

Usage

From source file:org.mitre.oauth2.introspectingfilter.service.impl.ScopeBasedIntrospectionAuthoritiesGranter.java

@Override
public List<GrantedAuthority> getAuthorities(JsonObject introspectionResponse) {
    List<GrantedAuthority> auth = new ArrayList<>(getAuthorities());

    if (introspectionResponse.has("scope") && introspectionResponse.get("scope").isJsonPrimitive()) {
        String scopeString = introspectionResponse.get("scope").getAsString();
        Set<String> scopes = OAuth2Utils.parseParameterList(scopeString);
        for (String scope : scopes) {
            auth.add(new SimpleGrantedAuthority("OAUTH_SCOPE_" + scope));
        }/* w w  w  .  j ava 2  s .  c  o m*/
    }

    return auth;
}

From source file:org.mitre.oauth2.assertion.impl.DirectCopyRequestFactory.java

@Override
public OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest, JWT assertion) {

    try {//from   w ww  . j a v  a  2s. c  o m
        JWTClaimsSet claims = assertion.getJWTClaimsSet();
        Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope"));

        Set<String> resources = Sets.newHashSet(claims.getAudience());

        return new OAuth2Request(tokenRequest.getRequestParameters(), client.getClientId(),
                client.getAuthorities(), true, scope, resources, null, null, null);
    } catch (ParseException e) {
        return null;
    }

}

From source file:nl.surfnet.coin.api.oauth.ImplicitGrantExplicitRedirectResolver.java

private boolean isImplicitGrant() {
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();/*from   www  .ja v a2  s.co  m*/
    String responseType = (String) requestAttributes.getRequest().getParameter("response_type");
    Set<String> responseTypes = OAuth2Utils.parseParameterList(responseType);
    return responseTypes.contains("token");
}

From source file:org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Deserializer.java

@Override
public OAuth2AccessToken deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    String tokenValue = null;/*from   w  ww. ja  va 2s .c  om*/
    String tokenType = null;
    String refreshToken = null;
    Long expiresIn = null;
    Set<String> scope = null;
    Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();

    // TODO What should occur if a parameter exists twice
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String name = jp.getCurrentName();
        jp.nextToken();
        if (OAuth2AccessToken.ACCESS_TOKEN.equals(name)) {
            tokenValue = jp.getText();
        } else if (OAuth2AccessToken.TOKEN_TYPE.equals(name)) {
            tokenType = jp.getText();
        } else if (OAuth2AccessToken.REFRESH_TOKEN.equals(name)) {
            refreshToken = jp.getText();
        } else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
            try {
                expiresIn = jp.getLongValue();
            } catch (JsonParseException e) {
                expiresIn = Long.valueOf(jp.getText());
            }
        } else if (OAuth2AccessToken.SCOPE.equals(name)) {
            String text = jp.getText();
            scope = OAuth2Utils.parseParameterList(text);
        } else {
            additionalInformation.put(name, jp.readValueAs(Object.class));
        }
    }

    // TODO What should occur if a required parameter (tokenValue or tokenType) is missing?

    DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenValue);
    accessToken.setTokenType(tokenType);
    if (expiresIn != null) {
        accessToken.setExpiration(new Date(System.currentTimeMillis() + (expiresIn * 1000)));
    }
    if (refreshToken != null) {
        accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken));
    }
    accessToken.setScope(scope);
    accessToken.setAdditionalInformation(additionalInformation);

    return accessToken;
}

From source file:org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.java

@Override
public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    JsonToken t = jp.getCurrentToken();/*  w  ww  . j  av  a 2  s  .c  om*/
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    Map<String, Object> errorParams = new HashMap<String, Object>();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        // Must point to field name
        String fieldName = jp.getCurrentName();
        // And then the value...
        t = jp.nextToken();
        // Note: must handle null explicitly here; value deserializers won't
        Object value;
        if (t == JsonToken.VALUE_NULL) {
            value = null;
        }
        // Some servers might send back complex content
        else if (t == JsonToken.START_ARRAY) {
            value = jp.readValueAs(List.class);
        } else if (t == JsonToken.START_OBJECT) {
            value = jp.readValueAs(Map.class);
        } else {
            value = jp.getText();
        }
        errorParams.put(fieldName, value);
    }

    Object errorCode = errorParams.get("error");
    String errorMessage = errorParams.containsKey("error_description")
            ? errorParams.get("error_description").toString()
            : null;
    if (errorMessage == null) {
        errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString();
    }

    OAuth2Exception ex;
    if ("invalid_client".equals(errorCode)) {
        ex = new InvalidClientException(errorMessage);
    } else if ("unauthorized_client".equals(errorCode)) {
        ex = new UnauthorizedUserException(errorMessage);
    } else if ("invalid_grant".equals(errorCode)) {
        if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) {
            ex = new RedirectMismatchException(errorMessage);
        } else {
            ex = new InvalidGrantException(errorMessage);
        }
    } else if ("invalid_scope".equals(errorCode)) {
        ex = new InvalidScopeException(errorMessage);
    } else if ("invalid_token".equals(errorCode)) {
        ex = new InvalidTokenException(errorMessage);
    } else if ("invalid_request".equals(errorCode)) {
        ex = new InvalidRequestException(errorMessage);
    } else if ("redirect_uri_mismatch".equals(errorCode)) {
        ex = new RedirectMismatchException(errorMessage);
    } else if ("unsupported_grant_type".equals(errorCode)) {
        ex = new UnsupportedGrantTypeException(errorMessage);
    } else if ("unsupported_response_type".equals(errorCode)) {
        ex = new UnsupportedResponseTypeException(errorMessage);
    } else if ("insufficient_scope".equals(errorCode)) {
        ex = new InsufficientScopeException(errorMessage,
                OAuth2Utils.parseParameterList((String) errorParams.get("scope")));
    } else if ("access_denied".equals(errorCode)) {
        ex = new UserDeniedAuthorizationException(errorMessage);
    } else {
        ex = new OAuth2Exception(errorMessage);
    }

    Set<Map.Entry<String, Object>> entries = errorParams.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        if (!"error".equals(key) && !"error_description".equals(key)) {
            Object value = entry.getValue();
            ex.addAdditionalInformation(key, value == null ? null : value.toString());
        }
    }

    return ex;

}

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 .j a  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));
    }/*from   w w w  .  ja  v a  2 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.example.ProxyAuthorizationServerTokenServices.java

private DefaultOAuth2AccessToken ectractAccessToken(Map<String, Object> map) {
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken((String) map.get("access_token"));
    token.setRefreshToken(new DefaultOAuth2RefreshToken((String) map.get("refresh_token")));
    token.setScope(OAuth2Utils.parseParameterList((String) map.get("scope")));
    return token;
}

From source file:org.mitre.oauth2.web.DeviceEndpoint.java

@RequestMapping(value = "/"
        + URL, method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String requestDeviceCode(@RequestParam("client_id") String clientId,
        @RequestParam(name = "scope", required = false) String scope, Map<String, String> parameters,
        ModelMap model) {/*from w w  w.j  a  v a  2  s. c o  m*/

    ClientDetailsEntity client;
    try {
        client = clientService.loadClientByClientId(clientId);

        // make sure this client can do the device flow

        Collection<String> authorizedGrantTypes = client.getAuthorizedGrantTypes();
        if (authorizedGrantTypes != null && !authorizedGrantTypes.isEmpty()
                && !authorizedGrantTypes.contains(DeviceTokenGranter.GRANT_TYPE)) {
            throw new InvalidClientException("Unauthorized grant type: " + DeviceTokenGranter.GRANT_TYPE);
        }

    } catch (IllegalArgumentException e) {
        logger.error("IllegalArgumentException was thrown when attempting to load client", e);
        model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        return HttpCodeView.VIEWNAME;
    }

    if (client == null) {
        logger.error("could not find client " + clientId);
        model.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }

    // make sure the client is allowed to ask for those scopes
    Set<String> requestedScopes = OAuth2Utils.parseParameterList(scope);
    Set<String> allowedScopes = client.getScope();

    if (!scopeService.scopesMatch(allowedScopes, requestedScopes)) {
        // client asked for scopes it can't have
        logger.error("Client asked for " + requestedScopes + " but is allowed " + allowedScopes);
        model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        model.put(JsonErrorView.ERROR, "invalid_scope");
        return JsonErrorView.VIEWNAME;
    }

    // if we got here the request is legit

    try {
        DeviceCode dc = deviceCodeService.createNewDeviceCode(requestedScopes, client, parameters);

        Map<String, Object> response = new HashMap<>();
        response.put("device_code", dc.getDeviceCode());
        response.put("user_code", dc.getUserCode());
        response.put("verification_uri", config.getIssuer() + USER_URL);
        if (client.getDeviceCodeValiditySeconds() != null) {
            response.put("expires_in", client.getDeviceCodeValiditySeconds());
        }

        if (config.isAllowCompleteDeviceCodeUri()) {
            URI verificationUriComplete = new URIBuilder(config.getIssuer() + USER_URL)
                    .addParameter("user_code", dc.getUserCode()).build();

            response.put("verification_uri_complete", verificationUriComplete.toString());
        }

        model.put(JsonEntityView.ENTITY, response);

        return JsonEntityView.VIEWNAME;
    } catch (DeviceCodeCreationException dcce) {

        model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        model.put(JsonErrorView.ERROR, dcce.getError());
        model.put(JsonErrorView.ERROR_MESSAGE, dcce.getMessage());

        return JsonErrorView.VIEWNAME;
    } catch (URISyntaxException use) {
        logger.error("unable to build verification_uri_complete due to wrong syntax of uri components");
        model.put(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR);

        return HttpCodeView.VIEWNAME;
    }

}

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

@RequestMapping(value = "/oauth2/rest_token", method = RequestMethod.POST)
@ResponseBody/*from   w w  w.ja  v  a 2s . 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;

}