Search in sources :

Example 1 with Jwt

use of org.gluu.oxauth.model.jwt.Jwt in project oxAuth by GluuFederation.

the class BackchannelAuthorizeRestWebServiceImpl method requestBackchannelAuthorizationPost.

@Override
public Response requestBackchannelAuthorizationPost(String clientId, String scope, String clientNotificationToken, String acrValues, String loginHintToken, String idTokenHint, String loginHint, String bindingMessage, String userCodeParam, Integer requestedExpiry, String request, String requestUri, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
    // it may be encoded
    scope = ServerUtil.urlDecode(scope);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.BACKCHANNEL_AUTHENTICATION);
    oAuth2AuditLog.setClientId(clientId);
    oAuth2AuditLog.setScope(scope);
    // ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final,
    // there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
    log.debug("Attempting to request backchannel authorization: " + "clientId = {}, scope = {}, clientNotificationToken = {}, acrValues = {}, loginHintToken = {}, " + "idTokenHint = {}, loginHint = {}, bindingMessage = {}, userCodeParam = {}, requestedExpiry = {}, " + "request= {}", clientId, scope, clientNotificationToken, acrValues, loginHintToken, idTokenHint, loginHint, bindingMessage, userCodeParam, requestedExpiry, request);
    log.debug("Attempting to request backchannel authorization: " + "isSecure = {}", securityContext.isSecure());
    Response.ResponseBuilder builder = Response.ok();
    if (!appConfiguration.getCibaEnabled()) {
        log.warn("Trying to register a CIBA request, however CIBA config is disabled.");
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    SessionClient sessionClient = identity.getSessionClient();
    Client client = null;
    if (sessionClient != null) {
        client = sessionClient.getClient();
    }
    if (client == null) {
        // 401
        builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_CLIENT));
        return builder.build();
    }
    if (!cibaRequestService.hasCibaCompatibility(client)) {
        // 401
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    List<String> scopes = new ArrayList<>();
    if (StringHelper.isNotEmpty(scope)) {
        Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
        scopes.addAll(grantedScopes);
    }
    JwtAuthorizationRequest jwtRequest = null;
    if (StringUtils.isNotBlank(request) || StringUtils.isNotBlank(requestUri)) {
        jwtRequest = JwtAuthorizationRequest.createJwtRequest(request, requestUri, client, null, cryptoProvider, appConfiguration);
        if (jwtRequest == null) {
            log.error("The JWT couldn't be processed");
            // 400
            builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
            builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
            throw new WebApplicationException(builder.build());
        }
        authorizeRestWebServiceValidator.validateCibaRequestObject(jwtRequest, client.getClientId());
        // JWT wins
        if (!jwtRequest.getScopes().isEmpty()) {
            scopes.addAll(scopeChecker.checkScopesPolicy(client, jwtRequest.getScopes()));
        }
        if (StringUtils.isNotBlank(jwtRequest.getClientNotificationToken())) {
            clientNotificationToken = jwtRequest.getClientNotificationToken();
        }
        if (StringUtils.isNotBlank(jwtRequest.getAcrValues())) {
            acrValues = jwtRequest.getAcrValues();
        }
        if (StringUtils.isNotBlank(jwtRequest.getLoginHintToken())) {
            loginHintToken = jwtRequest.getLoginHintToken();
        }
        if (StringUtils.isNotBlank(jwtRequest.getIdTokenHint())) {
            idTokenHint = jwtRequest.getIdTokenHint();
        }
        if (StringUtils.isNotBlank(jwtRequest.getLoginHint())) {
            loginHint = jwtRequest.getLoginHint();
        }
        if (StringUtils.isNotBlank(jwtRequest.getBindingMessage())) {
            bindingMessage = jwtRequest.getBindingMessage();
        }
        if (StringUtils.isNotBlank(jwtRequest.getUserCode())) {
            userCodeParam = jwtRequest.getUserCode();
        }
        if (jwtRequest.getRequestedExpiry() != null) {
            requestedExpiry = jwtRequest.getRequestedExpiry();
        } else if (jwtRequest.getExp() != null) {
            requestedExpiry = Math.toIntExact(jwtRequest.getExp() - System.currentTimeMillis() / 1000);
        }
    }
    if (appConfiguration.getFapiCompatibility() && jwtRequest == null) {
        // 400
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    User user = null;
    try {
        if (Strings.isNotBlank(loginHint)) {
            // login_hint
            user = userService.getUniqueUserByAttributes(appConfiguration.getBackchannelLoginHintClaims(), loginHint);
        } else if (Strings.isNotBlank(idTokenHint)) {
            // id_token_hint
            AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
            if (authorizationGrant == null) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            user = authorizationGrant.getUser();
        }
        if (Strings.isNotBlank(loginHintToken)) {
            // login_hint_token
            Jwt jwt = Jwt.parse(loginHintToken);
            SignatureAlgorithm algorithm = jwt.getHeader().getSignatureAlgorithm();
            String keyId = jwt.getHeader().getKeyId();
            if (algorithm == null || Strings.isBlank(keyId)) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            boolean validSignature = false;
            if (algorithm.getFamily() == AlgorithmFamily.RSA) {
                RSAPublicKey publicKey = JwkClient.getRSAPublicKey(client.getJwksUri(), keyId);
                RSASigner rsaSigner = new RSASigner(algorithm, publicKey);
                validSignature = rsaSigner.validate(jwt);
            } else if (algorithm.getFamily() == AlgorithmFamily.EC) {
                ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(client.getJwksUri(), keyId);
                ECDSASigner ecdsaSigner = new ECDSASigner(algorithm, publicKey);
                validSignature = ecdsaSigner.validate(jwt);
            }
            if (!validSignature) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            JSONObject subject = jwt.getClaims().getClaimAsJSON("subject");
            if (subject == null || !subject.has("subject_type") || !subject.has(subject.getString("subject_type"))) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            String subjectTypeKey = subject.getString("subject_type");
            String subjectTypeValue = subject.getString(subjectTypeKey);
            user = userService.getUniqueUserByAttributes(appConfiguration.getBackchannelLoginHintClaims(), subjectTypeValue);
        }
    } catch (InvalidJwtException e) {
        log.error(e.getMessage(), e);
    } catch (JSONException e) {
        log.error(e.getMessage(), e);
    }
    if (user == null) {
        // 400
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
        return builder.build();
    }
    try {
        String userCode = (String) user.getAttribute("oxAuthBackchannelUserCode", true, false);
        DefaultErrorResponse cibaAuthorizeParamsValidation = cibaAuthorizeParamsValidatorService.validateParams(scopes, clientNotificationToken, client.getBackchannelTokenDeliveryMode(), loginHintToken, idTokenHint, loginHint, bindingMessage, client.getBackchannelUserCodeParameter(), userCodeParam, userCode, requestedExpiry);
        if (cibaAuthorizeParamsValidation != null) {
            builder = Response.status(cibaAuthorizeParamsValidation.getStatus());
            builder.entity(errorResponseFactory.errorAsJson(cibaAuthorizeParamsValidation.getType(), cibaAuthorizeParamsValidation.getReason()));
            return builder.build();
        }
        String deviceRegistrationToken = (String) user.getAttribute("oxAuthBackchannelDeviceRegistrationToken", true, false);
        if (deviceRegistrationToken == null) {
            // 401
            builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode());
            builder.entity(errorResponseFactory.getErrorAsJson(UNAUTHORIZED_END_USER_DEVICE));
            return builder.build();
        }
        int expiresIn = requestedExpiry != null ? requestedExpiry : appConfiguration.getBackchannelAuthenticationResponseExpiresIn();
        Integer interval = client.getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.PUSH ? null : appConfiguration.getBackchannelAuthenticationResponseInterval();
        long currentTime = new Date().getTime();
        CibaRequestCacheControl cibaRequestCacheControl = new CibaRequestCacheControl(user, client, expiresIn, scopes, clientNotificationToken, bindingMessage, currentTime, acrValues);
        cibaRequestService.save(cibaRequestCacheControl, expiresIn);
        String authReqId = cibaRequestCacheControl.getAuthReqId();
        // Notify End-User to obtain Consent/Authorization
        cibaEndUserNotificationService.notifyEndUser(cibaRequestCacheControl.getScopesAsString(), cibaRequestCacheControl.getAcrValues(), authReqId, deviceRegistrationToken);
        builder.entity(getJSONObject(authReqId, expiresIn, interval).toString(4).replace("\\/", "/"));
        builder.type(MediaType.APPLICATION_JSON_TYPE);
        builder.cacheControl(ServerUtil.cacheControl(true, false));
    } catch (JSONException e) {
        builder = Response.status(400);
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        log.error(e.getMessage(), e);
    } catch (InvalidClaimException e) {
        builder = Response.status(400);
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(org.gluu.oxauth.model.session.SessionClient) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) ArrayList(java.util.ArrayList) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) InvalidClaimException(org.gluu.oxauth.model.exception.InvalidClaimException) RSAPublicKey(org.gluu.oxauth.model.crypto.signature.RSAPublicKey) RSASigner(org.gluu.oxauth.model.jws.RSASigner) JwtAuthorizationRequest(org.gluu.oxauth.model.authorize.JwtAuthorizationRequest) SessionClient(org.gluu.oxauth.model.session.SessionClient) Client(org.gluu.oxauth.model.registration.Client) JwkClient(org.gluu.oxauth.client.JwkClient) DefaultErrorResponse(org.gluu.oxauth.model.error.DefaultErrorResponse) ECDSAPublicKey(org.gluu.oxauth.model.crypto.signature.ECDSAPublicKey) ECDSASigner(org.gluu.oxauth.model.jws.ECDSASigner) Jwt(org.gluu.oxauth.model.jwt.Jwt) JSONException(org.json.JSONException) Date(java.util.Date) DefaultErrorResponse(org.gluu.oxauth.model.error.DefaultErrorResponse) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONObject(org.json.JSONObject)

Example 2 with Jwt

use of org.gluu.oxauth.model.jwt.Jwt in project oxAuth by GluuFederation.

the class IntrospectionWebService method createResponseAsJwt.

private String createResponseAsJwt(JSONObject response, AuthorizationGrant grant) throws Exception {
    final JwtSigner jwtSigner = JwtSigner.newJwtSigner(appConfiguration, webKeysConfiguration, grant.getClient());
    final Jwt jwt = jwtSigner.newJwt();
    Audience.setAudience(jwt.getClaims(), grant.getClient());
    Iterator<String> keysIter = response.keys();
    while (keysIter.hasNext()) {
        String key = keysIter.next();
        Object value = response.opt(key);
        if (value != null) {
            try {
                jwt.getClaims().setClaimObject(key, value, false);
            } catch (Exception e) {
                log.error("Failed to put claims into jwt. Key: " + key + ", response: " + response.toString(), e);
            }
        }
    }
    return jwtSigner.sign().toString();
}
Also used : JwtSigner(org.gluu.oxauth.model.token.JwtSigner) Jwt(org.gluu.oxauth.model.jwt.Jwt) JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 3 with Jwt

use of org.gluu.oxauth.model.jwt.Jwt in project oxAuth by GluuFederation.

the class AuthorizationCodeFlowEmbeddedTest method completeFlowWithOptionalNonceStep2.

@Parameters({ "tokenPath", "validateTokenPath", "redirectUri" })
@Test(dependsOnMethods = { "dynamicClientRegistration", "completeFlowWithOptionalNonceStep1" }, priority = 20)
public void completeFlowWithOptionalNonceStep2(final String tokenPath, final String validateTokenPath, final String redirectUri) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();
    org.gluu.oxauth.client.TokenRequest tokenRequest = new org.gluu.oxauth.client.TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode4);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());
    Response response = request.post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);
    showResponse("completeFlowWithOptionalNonceStep2", response, entity);
    assertEquals(response.getStatus(), 200, "Unexpected response code.");
    assertTrue(response.getHeaderString("Cache-Control") != null && response.getHeaderString("Cache-Control").equals("no-store"), "Unexpected result: " + response.getHeaderString("Cache-Control"));
    assertTrue(response.getHeaderString("Pragma") != null && response.getHeaderString("Pragma").equals("no-cache"), "Unexpected result: " + response.getHeaderString("Pragma"));
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("access_token"), "Unexpected result: access_token not found");
        assertTrue(jsonObj.has("token_type"), "Unexpected result: token_type not found");
        assertTrue(jsonObj.has("refresh_token"), "Unexpected result: refresh_token not found");
        assertTrue(jsonObj.has("id_token"), "Unexpected result: id_token not found");
        String accessToken = jsonObj.getString("access_token");
        refreshToken3 = jsonObj.getString("refresh_token");
        String idToken = jsonObj.getString("id_token");
        Jwt jwt = Jwt.parse(idToken);
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.NONCE));
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : Jwt(org.gluu.oxauth.model.jwt.Jwt) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) Builder(javax.ws.rs.client.Invocation.Builder) JSONException(org.json.JSONException) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) Response(javax.ws.rs.core.Response) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) JSONObject(org.json.JSONObject) org.gluu.oxauth.client(org.gluu.oxauth.client) Parameters(org.testng.annotations.Parameters) BaseTest(org.gluu.oxauth.BaseTest) Test(org.testng.annotations.Test)

Example 4 with Jwt

use of org.gluu.oxauth.model.jwt.Jwt in project oxAuth by GluuFederation.

the class SectorIdentifierUrlVerificationEmbeddedTest method requestAuthorizationCodeWithSectorIdentifierStep2.

// This test requires a place to publish a sector identifier JSON array of
// redirect URIs via HTTPS
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" })
@Test(dependsOnMethods = "requestAuthorizationCodeWithSectorIdentifierStep1")
public void requestAuthorizationCodeWithSectorIdentifierStep2(final String authorizePath, final String userId, final String userSecret, final String redirectUri) throws Exception {
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String state = UUID.randomUUID().toString();
    String nonce = UUID.randomUUID().toString();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId1, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    authorizationRequest.getPrompts().add(Prompt.NONE);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
    request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
    request.header("Accept", MediaType.TEXT_PLAIN);
    Response response = request.get();
    String entity = response.readEntity(String.class);
    showResponse("requestAuthorizationCodeWithSectorIdentifierStep2", response, entity);
    assertEquals(response.getStatus(), 302, "Unexpected response code.");
    assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());
    try {
        URI uri = new URI(response.getLocation().toString());
        assertNotNull(uri.getFragment());
        Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());
        assertNotNull(params.get(AuthorizeResponseParam.CODE), "The code is null");
        assertNotNull(params.get(AuthorizeResponseParam.ID_TOKEN), "The ID Token is null");
        assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope is null");
        assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null");
        String idToken = params.get(AuthorizeResponseParam.ID_TOKEN);
        Jwt jwt = Jwt.parse(idToken);
        assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
        assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.CODE_HASH));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME));
    } catch (URISyntaxException e) {
        e.printStackTrace();
        fail("Response URI is not well formed");
    } catch (InvalidJwtException e) {
        e.printStackTrace();
        fail("Invalid JWT");
    }
}
Also used : Response(javax.ws.rs.core.Response) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) AuthorizationRequest(org.gluu.oxauth.client.AuthorizationRequest) Jwt(org.gluu.oxauth.model.jwt.Jwt) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) Builder(javax.ws.rs.client.Invocation.Builder) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) REGISTRATION_CLIENT_URI(org.gluu.oxauth.model.register.RegisterResponseParam.REGISTRATION_CLIENT_URI) ResponseType(org.gluu.oxauth.model.common.ResponseType) Parameters(org.testng.annotations.Parameters) BaseTest(org.gluu.oxauth.BaseTest) Test(org.testng.annotations.Test)

Example 5 with Jwt

use of org.gluu.oxauth.model.jwt.Jwt in project oxAuth by GluuFederation.

the class MultivaluedClaims method authorizationRequestObjectWithMultivaluedClaimRS256.

@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri", "RS256_keyId", "clientJwksUri" })
@Test
public void authorizationRequestObjectWithMultivaluedClaimRS256(final String userId, final String userSecret, final String redirectUri, final String redirectUris, final String dnName, final String keyStoreFile, final String keyStoreSecret, final String sectorIdentifierUri, final String keyId, final String clientJwksUri) throws Exception {
    showTitle("authorizationRequestObjectWithMultivaluedClaimRS256");
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.RS256);
    registerRequest.setUserInfoSignedResponseAlg(SignatureAlgorithm.RS256);
    registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS256);
    registerRequest.setJwksUri(clientJwksUri);
    registerRequest.setClaims(Arrays.asList("member_of"));
    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();
    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());
    String clientId = registerResponse.getClientId();
    // 2. Request authorization
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);
    List<String> scopes = Arrays.asList("openid");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest, SignatureAlgorithm.RS256, cryptoProvider);
    jwtAuthorizationRequest.setKeyId(keyId);
    jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createEssential(true)));
    jwtAuthorizationRequest.addIdTokenClaim(new Claim("member_of", ClaimValue.createEssential(true)));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim("member_of", ClaimValue.createEssential(true)));
    String authJwt = jwtAuthorizationRequest.getEncodedJwt();
    authorizationRequest.setRequest(authJwt);
    AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setRequest(authorizationRequest);
    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(authorizationEndpoint, authorizationRequest, userId, userSecret);
    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getAccessToken(), "The accessToken is null");
    assertNotNull(authorizationResponse.getTokenType(), "The tokenType is null");
    assertNotNull(authorizationResponse.getIdToken(), "The idToken is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");
    String idToken = authorizationResponse.getIdToken();
    String accessToken = authorizationResponse.getAccessToken();
    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ACCESS_TOKEN_HASH));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME));
    assertNotNull(jwt.getClaims().getClaimAsStringList("member_of"));
    assertTrue(jwt.getClaims().getClaimAsStringList("member_of").size() > 1);
    RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwksUri, jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);
    assertTrue(rsaSigner.validate(jwt));
    // 4. Request user info
    UserInfoRequest userInfoRequest = new UserInfoRequest(accessToken);
    UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
    userInfoClient.setRequest(userInfoRequest);
    userInfoClient.setJwksUri(jwksUri);
    UserInfoResponse userInfoResponse = userInfoClient.exec();
    showClient(userInfoClient);
    assertEquals(userInfoResponse.getStatus(), 200, "Unexpected response code: " + userInfoResponse.getStatus());
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(userInfoResponse.getClaim("member_of"));
    assertTrue(userInfoResponse.getClaim("member_of").size() > 1);
}
Also used : RegisterRequest(org.gluu.oxauth.client.RegisterRequest) JwtAuthorizationRequest(org.gluu.oxauth.client.model.authorize.JwtAuthorizationRequest) AuthorizationRequest(org.gluu.oxauth.client.AuthorizationRequest) Jwt(org.gluu.oxauth.model.jwt.Jwt) UserInfoRequest(org.gluu.oxauth.client.UserInfoRequest) UserInfoClient(org.gluu.oxauth.client.UserInfoClient) ResponseType(org.gluu.oxauth.model.common.ResponseType) AuthorizationResponse(org.gluu.oxauth.client.AuthorizationResponse) OxAuthCryptoProvider(org.gluu.oxauth.model.crypto.OxAuthCryptoProvider) RegisterResponse(org.gluu.oxauth.client.RegisterResponse) RSAPublicKey(org.gluu.oxauth.model.crypto.signature.RSAPublicKey) RegisterClient(org.gluu.oxauth.client.RegisterClient) RSASigner(org.gluu.oxauth.model.jws.RSASigner) JwtAuthorizationRequest(org.gluu.oxauth.client.model.authorize.JwtAuthorizationRequest) UserInfoResponse(org.gluu.oxauth.client.UserInfoResponse) AuthorizeClient(org.gluu.oxauth.client.AuthorizeClient) Claim(org.gluu.oxauth.client.model.authorize.Claim) Parameters(org.testng.annotations.Parameters) BaseTest(org.gluu.oxauth.BaseTest) Test(org.testng.annotations.Test)

Aggregations

Jwt (org.gluu.oxauth.model.jwt.Jwt)244 Test (org.testng.annotations.Test)217 BaseTest (org.gluu.oxauth.BaseTest)215 Parameters (org.testng.annotations.Parameters)210 AuthorizationResponse (org.gluu.oxauth.client.AuthorizationResponse)171 ResponseType (org.gluu.oxauth.model.common.ResponseType)170 RegisterResponse (org.gluu.oxauth.client.RegisterResponse)167 AuthorizationRequest (org.gluu.oxauth.client.AuthorizationRequest)162 RegisterClient (org.gluu.oxauth.client.RegisterClient)156 RegisterRequest (org.gluu.oxauth.client.RegisterRequest)156 OxAuthCryptoProvider (org.gluu.oxauth.model.crypto.OxAuthCryptoProvider)108 RSASigner (org.gluu.oxauth.model.jws.RSASigner)98 RSAPublicKey (org.gluu.oxauth.model.crypto.signature.RSAPublicKey)97 AuthorizeClient (org.gluu.oxauth.client.AuthorizeClient)92 UserInfoResponse (org.gluu.oxauth.client.UserInfoResponse)82 UserInfoClient (org.gluu.oxauth.client.UserInfoClient)81 JwtAuthorizationRequest (org.gluu.oxauth.client.model.authorize.JwtAuthorizationRequest)70 JSONObject (org.json.JSONObject)60 Claim (org.gluu.oxauth.client.model.authorize.Claim)46 UserInfoRequest (org.gluu.oxauth.client.UserInfoRequest)39