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

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

Introduction

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

Prototype

public void setClientId(String clientId) 

Source Link

Usage

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

/**
 * @param inputParams//from ww w.  j  ava  2 s.  c o  m
 * @return
 */
private void processRequestObject(String jwtString, AuthorizationRequest request) {

    // parse the request object
    try {
        JWT jwt = JWTParser.parse(jwtString);

        if (jwt instanceof SignedJWT) {
            // it's a signed JWT, check the signature

            SignedJWT signedJwt = (SignedJWT) jwt;

            // need to check clientId first so that we can load the client to check other fields
            if (request.getClientId() == null) {
                request.setClientId(signedJwt.getJWTClaimsSet().getStringClaim(CLIENT_ID));
            }

            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if (client == null) {
                throw new InvalidClientException("Client not found: " + request.getClientId());
            }

            JWSAlgorithm alg = signedJwt.getHeader().getAlgorithm();

            if (client.getRequestObjectSigningAlg() == null
                    || !client.getRequestObjectSigningAlg().equals(alg)) {
                throw new InvalidClientException("Client's registered request object signing algorithm ("
                        + client.getRequestObjectSigningAlg()
                        + ") does not match request object's actual algorithm (" + alg.getName() + ")");
            }

            JWTSigningAndValidationService validator = validators.getValidator(client, alg);

            if (validator == null) {
                throw new InvalidClientException(
                        "Unable to create signature validator for client " + client + " and algorithm " + alg);
            }

            if (!validator.validateSignature(signedJwt)) {
                throw new InvalidClientException(
                        "Signature did not validate for presented JWT request object.");
            }

        } else if (jwt instanceof PlainJWT) {
            PlainJWT plainJwt = (PlainJWT) jwt;

            // need to check clientId first so that we can load the client to check other fields
            if (request.getClientId() == null) {
                request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim(CLIENT_ID));
            }

            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if (client == null) {
                throw new InvalidClientException("Client not found: " + request.getClientId());
            }

            if (client.getRequestObjectSigningAlg() == null) {
                throw new InvalidClientException(
                        "Client is not registered for unsigned request objects (no request_object_signing_alg registered)");
            } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) {
                throw new InvalidClientException(
                        "Client is not registered for unsigned request objects (request_object_signing_alg is "
                                + client.getRequestObjectSigningAlg() + ")");
            }

            // if we got here, we're OK, keep processing

        } else if (jwt instanceof EncryptedJWT) {

            EncryptedJWT encryptedJWT = (EncryptedJWT) jwt;

            // decrypt the jwt if we can

            encryptionService.decryptJwt(encryptedJWT);

            // TODO: what if the content is a signed JWT? (#525)

            if (!encryptedJWT.getState().equals(State.DECRYPTED)) {
                throw new InvalidClientException("Unable to decrypt the request object");
            }

            // need to check clientId first so that we can load the client to check other fields
            if (request.getClientId() == null) {
                request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim(CLIENT_ID));
            }

            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if (client == null) {
                throw new InvalidClientException("Client not found: " + request.getClientId());
            }

        }

        /*
         * NOTE: Claims inside the request object always take precedence over those in the parameter map.
         */

        // now that we've got the JWT, and it's been parsed, validated, and/or decrypted, we can process the claims

        JWTClaimsSet claims = jwt.getJWTClaimsSet();

        Set<String> responseTypes = OAuth2Utils.parseParameterList(claims.getStringClaim(RESPONSE_TYPE));
        if (responseTypes != null && !responseTypes.isEmpty()) {
            if (!responseTypes.equals(request.getResponseTypes())) {
                logger.info(
                        "Mismatch between request object and regular parameter for response_type, using request object");
            }
            request.setResponseTypes(responseTypes);
        }

        String redirectUri = claims.getStringClaim(REDIRECT_URI);
        if (redirectUri != null) {
            if (!redirectUri.equals(request.getRedirectUri())) {
                logger.info(
                        "Mismatch between request object and regular parameter for redirect_uri, using request object");
            }
            request.setRedirectUri(redirectUri);
        }

        String state = claims.getStringClaim(STATE);
        if (state != null) {
            if (!state.equals(request.getState())) {
                logger.info(
                        "Mismatch between request object and regular parameter for state, using request object");
            }
            request.setState(state);
        }

        String nonce = claims.getStringClaim(NONCE);
        if (nonce != null) {
            if (!nonce.equals(request.getExtensions().get(NONCE))) {
                logger.info(
                        "Mismatch between request object and regular parameter for nonce, using request object");
            }
            request.getExtensions().put(NONCE, nonce);
        }

        String display = claims.getStringClaim(DISPLAY);
        if (display != null) {
            if (!display.equals(request.getExtensions().get(DISPLAY))) {
                logger.info(
                        "Mismatch between request object and regular parameter for display, using request object");
            }
            request.getExtensions().put(DISPLAY, display);
        }

        String prompt = claims.getStringClaim(PROMPT);
        if (prompt != null) {
            if (!prompt.equals(request.getExtensions().get(PROMPT))) {
                logger.info(
                        "Mismatch between request object and regular parameter for prompt, using request object");
            }
            request.getExtensions().put(PROMPT, prompt);
        }

        Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim(SCOPE));
        if (scope != null && !scope.isEmpty()) {
            if (!scope.equals(request.getScope())) {
                logger.info(
                        "Mismatch between request object and regular parameter for scope, using request object");
            }
            request.setScope(scope);
        }

        JsonObject claimRequest = parseClaimRequest(claims.getStringClaim(CLAIMS));
        if (claimRequest != null) {
            if (!claimRequest.equals(parseClaimRequest(request.getExtensions().get(CLAIMS).toString()))) {
                logger.info(
                        "Mismatch between request object and regular parameter for claims, using request object");
            }
            // we save the string because the object might not be a Java Serializable, and we can parse it easily enough anyway
            request.getExtensions().put(CLAIMS, claimRequest.toString());
        }

        String loginHint = claims.getStringClaim(LOGIN_HINT);
        if (loginHint != null) {
            if (!loginHint.equals(request.getExtensions().get(LOGIN_HINT))) {
                logger.info(
                        "Mistmatch between request object and regular parameter for login_hint, using requst object");
            }
            request.getExtensions().put(LOGIN_HINT, loginHint);
        }

    } catch (ParseException e) {
        logger.error("ParseException while parsing RequestObject:", e);
    }
}

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

/**
 * @param inputParams/*from www  .  ja v  a2s.  co  m*/
 * @return
 */
private void processRequestObject(String jwtString, AuthorizationRequest request) {

    // parse the request object
    try {
        JWT jwt = JWTParser.parse(jwtString);

        // TODO: check parameter consistency, move keys to constants

        if (jwt instanceof SignedJWT) {
            // it's a signed JWT, check the signature

            SignedJWT signedJwt = (SignedJWT) jwt;

            // need to check clientId first so that we can load the client to check other fields
            if (request.getClientId() == null) {
                request.setClientId(signedJwt.getJWTClaimsSet().getStringClaim("client_id"));
            }

            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if (client == null) {
                throw new InvalidClientException("Client not found: " + request.getClientId());
            }

            JWSAlgorithm alg = signedJwt.getHeader().getAlgorithm();

            if (client.getRequestObjectSigningAlg() != null) {
                if (!client.getRequestObjectSigningAlg().equals(alg)) {
                    throw new InvalidClientException("Client's registered request object signing algorithm ("
                            + client.getRequestObjectSigningAlg()
                            + ") does not match request object's actual algorithm (" + alg.getName() + ")");
                }
            }

            if (alg.equals(JWSAlgorithm.RS256) || alg.equals(JWSAlgorithm.RS384)
                    || alg.equals(JWSAlgorithm.RS512)) {

                // it's RSA, need to find the JWK URI and fetch the key 

                if (client.getJwksUri() == null) {
                    throw new InvalidClientException(
                            "Client must have a JWKS URI registered to use signed request objects.");
                }

                // check JWT signature
                JwtSigningAndValidationService validator = validators.getValidator(client.getJwksUri());

                if (validator == null) {
                    throw new InvalidClientException(
                            "Unable to create signature validator for client's JWKS URI: "
                                    + client.getJwksUri());
                }

                if (!validator.validateSignature(signedJwt)) {
                    throw new InvalidClientException(
                            "Signature did not validate for presented JWT request object.");
                }
            } else if (alg.equals(JWSAlgorithm.HS256) || alg.equals(JWSAlgorithm.HS384)
                    || alg.equals(JWSAlgorithm.HS512)) {

                // it's HMAC, we need to make a validator based on the client secret

                JwtSigningAndValidationService validator = getSymmetricValidtor(client);

                if (validator == null) {
                    throw new InvalidClientException(
                            "Unable to create signature validator for client's secret: "
                                    + client.getClientSecret());
                }

                if (!validator.validateSignature(signedJwt)) {
                    throw new InvalidClientException(
                            "Signature did not validate for presented JWT request object.");
                }

            }

        } else if (jwt instanceof PlainJWT) {
            PlainJWT plainJwt = (PlainJWT) jwt;

            // need to check clientId first so that we can load the client to check other fields
            if (request.getClientId() == null) {
                request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim("client_id"));
            }

            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if (client == null) {
                throw new InvalidClientException("Client not found: " + request.getClientId());
            }

            if (client.getRequestObjectSigningAlg() == null) {
                throw new InvalidClientException(
                        "Client is not registered for unsigned request objects (no request_object_signing_alg registered)");
            } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) {
                throw new InvalidClientException(
                        "Client is not registered for unsigned request objects (request_object_signing_alg is "
                                + client.getRequestObjectSigningAlg() + ")");
            }

            // if we got here, we're OK, keep processing

        } else if (jwt instanceof EncryptedJWT) {

            EncryptedJWT encryptedJWT = (EncryptedJWT) jwt;

            // decrypt the jwt if we can

            encryptionService.decryptJwt(encryptedJWT);

            if (!encryptedJWT.getState().equals(State.DECRYPTED)) {
                throw new InvalidClientException("Unable to decrypt the request object");
            }

            // need to check clientId first so that we can load the client to check other fields
            if (request.getClientId() == null) {
                request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim("client_id"));
            }

            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if (client == null) {
                throw new InvalidClientException("Client not found: " + request.getClientId());
            }

        }

        /*
         * Claims precedence order logic:
         * 
         * if (in Claims):
         *       if (in params):
         *          if (equal):
         *             OK
         *          else (not equal):
         *             error
         *       else (not in params):
         *          add to params
         * else (not in claims):
         *       we don't care
         */

        // now that we've got the JWT, and it's been parsed, validated, and/or decrypted, we can process the claims

        ReadOnlyJWTClaimsSet claims = jwt.getJWTClaimsSet();

        Set<String> responseTypes = OAuth2Utils.parseParameterList(claims.getStringClaim("response_type"));
        if (responseTypes != null && !responseTypes.isEmpty()) {
            if (request.getResponseTypes() == null || request.getResponseTypes().isEmpty()) {
                // if it's null or empty, we fill in the value with what we were passed
                request.setResponseTypes(responseTypes);
            } else if (!request.getResponseTypes().equals(responseTypes)) {
                // FIXME: throw an error               
            }
        }

        String redirectUri = claims.getStringClaim("redirect_uri");
        if (redirectUri != null) {
            if (request.getRedirectUri() == null) {
                request.setRedirectUri(redirectUri);
            } else if (!request.getRedirectUri().equals(redirectUri)) {
                // FIXME: throw an error
            }
        }

        String state = claims.getStringClaim("state");
        if (state != null) {
            if (request.getState() == null) {
                request.setState(state);
            } else if (!request.getState().equals(state)) {
                // FIXME: throw an error
            }
        }

        String nonce = claims.getStringClaim("nonce");
        if (nonce != null) {
            if (request.getExtensions().get("nonce") == null) {
                request.getExtensions().put("nonce", nonce);
            } else if (!request.getExtensions().get("nonce").equals(nonce)) {
                // FIXME: throw an error
            }
        }

        String display = claims.getStringClaim("display");
        if (display != null) {
            if (request.getExtensions().get("display") == null) {
                request.getExtensions().put("display", display);
            } else if (!request.getExtensions().get("display").equals(display)) {
                // FIXME: throw an error
            }
        }

        String prompt = claims.getStringClaim("prompt");
        if (prompt != null) {
            if (request.getExtensions().get("prompt") == null) {
                request.getExtensions().put("prompt", prompt);
            } else if (!request.getExtensions().get("prompt").equals(prompt)) {
                // FIXME: throw an error
            }
        }

        Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope"));
        if (scope != null && !scope.isEmpty()) {
            if (request.getScope() == null || request.getScope().isEmpty()) {
                request.setScope(scope);
            } else if (!request.getScope().equals(scope)) {
                // FIXME: throw an error
            }
        }

        JsonObject claimRequest = parseClaimRequest(claims.getStringClaim("claims"));
        if (claimRequest != null) {
            if (request.getExtensions().get("claims") == null) {
                // we save the string because the object might not serialize
                request.getExtensions().put("claims", claimRequest.toString());
            } else if (parseClaimRequest(request.getExtensions().get("claims").toString())
                    .equals(claimRequest)) {
                // FIXME: throw an error
            }
        }

    } catch (ParseException e) {
        logger.error("ParseException while parsing RequestObject:", e);
    }
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void testOpenIdTokenHybridFlowWithNoImplicitGrantWhenLenientWhenAppNotApproved() throws Exception {
    String clientId = "testclient" + generator.generate();
    String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid";
    setUpClients(clientId, scopes, scopes, "authorization_code", false);
    String username = "testuser" + generator.generate();
    String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZoneHolder.get().getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest();
    authorizationRequest.setClientId(clientId);
    authorizationRequest.setRedirectUri(TEST_REDIRECT_URI);
    authorizationRequest.setScope(new ArrayList<>(Arrays.asList("openid")));
    authorizationRequest.setResponseTypes(new TreeSet<>(Arrays.asList("code", "id_token")));
    authorizationRequest.setState(state);

    session.setAttribute("authorizationRequest", authorizationRequest);

    MvcResult result = getMockMvc()/* ww w  .j  a  va2  s. c o  m*/
            .perform(post("/oauth/authorize").session(session).with(cookieCsrf())
                    .param(OAuth2Utils.USER_OAUTH_APPROVAL, "true").param("scope.0", "openid"))
            .andExpect(status().is3xxRedirection()).andReturn();

    URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?"));
    Map query = splitQuery(url);
    assertNotNull(query.get("code"));
    String code = ((List<String>) query.get("code")).get(0);
    assertNotNull(code);
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void testOpenIdTokenHybridFlowWithNoImplicitGrantWhenStrictWhenAppNotApproved() throws Exception {
    String clientId = "testclient" + generator.generate();
    String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid";
    setUpClients(clientId, scopes, scopes, "authorization_code", false);
    String username = "testuser" + generator.generate();
    String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZoneHolder.get().getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest();
    authorizationRequest.setClientId(clientId);
    authorizationRequest.setRedirectUri(TEST_REDIRECT_URI);
    authorizationRequest.setScope(new ArrayList<>(Arrays.asList("openid")));
    authorizationRequest.setResponseTypes(new TreeSet<>(Arrays.asList("code", "id_token")));
    authorizationRequest.setState(state);
    session.setAttribute("authorizationRequest", authorizationRequest);

    MvcResult result = getMockMvc()//from ww w.ja v a2 s. c  o m
            .perform(post("/oauth/authorize").session(session).param(OAuth2Utils.USER_OAUTH_APPROVAL, "true")
                    .with(cookieCsrf()).param("scope.0", "openid"))
            .andExpect(status().is3xxRedirection()).andReturn();

    URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?"));
    Map query = splitQuery(url);
    assertNotNull(query.get("id_token"));
    assertNotNull(((List) query.get("id_token")).get(0));
    assertNotNull(((List) query.get("code")).get(0));
    assertNull(query.get("token"));
}