Search in sources :

Example 1 with RSASigner

use of org.gluu.oxauth.model.jws.RSASigner 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 RSASigner

use of org.gluu.oxauth.model.jws.RSASigner 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)

Example 3 with RSASigner

use of org.gluu.oxauth.model.jws.RSASigner in project oxAuth by GluuFederation.

the class MultivaluedClaims method authorizationRequestWithMultivaluedClaimPS384.

@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "sectorIdentifierUri" })
@Test
public void authorizationRequestWithMultivaluedClaimPS384(final String userId, final String userSecret, final String redirectUri, final String redirectUris, final String sectorIdentifierUri) throws Exception {
    showTitle("authorizationRequestWithMultivaluedClaimPS384");
    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.setUserInfoSignedResponseAlg(SignatureAlgorithm.PS384);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.PS384);
    registerRequest.addCustomAttribute("oxIncludeClaimsInIdToken", "true");
    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
    List<String> scopes = Arrays.asList("openid", "test");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    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.PS384, 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) 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) UserInfoResponse(org.gluu.oxauth.client.UserInfoResponse) AuthorizeClient(org.gluu.oxauth.client.AuthorizeClient) Parameters(org.testng.annotations.Parameters) BaseTest(org.gluu.oxauth.BaseTest) Test(org.testng.annotations.Test)

Example 4 with RSASigner

use of org.gluu.oxauth.model.jws.RSASigner in project oxAuth by GluuFederation.

the class MultivaluedClaims method authorizationRequestObjectWithMultivaluedClaimRS512.

@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri", "RS512_keyId", "clientJwksUri" })
@Test
public void authorizationRequestObjectWithMultivaluedClaimRS512(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("authorizationRequestObjectWithMultivaluedClaimRS512");
    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.RS512);
    registerRequest.setUserInfoSignedResponseAlg(SignatureAlgorithm.RS512);
    registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS512);
    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.RS512, 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.RS512, 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)

Example 5 with RSASigner

use of org.gluu.oxauth.model.jws.RSASigner in project oxAuth by GluuFederation.

the class MultivaluedClaims method authorizationRequestWithMultivaluedClaimPS512.

@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "sectorIdentifierUri" })
@Test
public void authorizationRequestWithMultivaluedClaimPS512(final String userId, final String userSecret, final String redirectUri, final String redirectUris, final String sectorIdentifierUri) throws Exception {
    showTitle("authorizationRequestWithMultivaluedClaimPS512");
    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.setUserInfoSignedResponseAlg(SignatureAlgorithm.PS512);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.PS512);
    registerRequest.addCustomAttribute("oxIncludeClaimsInIdToken", "true");
    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
    List<String> scopes = Arrays.asList("openid", "test");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    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.PS512, 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) 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) UserInfoResponse(org.gluu.oxauth.client.UserInfoResponse) AuthorizeClient(org.gluu.oxauth.client.AuthorizeClient) Parameters(org.testng.annotations.Parameters) BaseTest(org.gluu.oxauth.BaseTest) Test(org.testng.annotations.Test)

Aggregations

RSASigner (org.gluu.oxauth.model.jws.RSASigner)102 RSAPublicKey (org.gluu.oxauth.model.crypto.signature.RSAPublicKey)101 Jwt (org.gluu.oxauth.model.jwt.Jwt)98 BaseTest (org.gluu.oxauth.BaseTest)93 Test (org.testng.annotations.Test)93 AuthorizationResponse (org.gluu.oxauth.client.AuthorizationResponse)92 RegisterResponse (org.gluu.oxauth.client.RegisterResponse)90 ResponseType (org.gluu.oxauth.model.common.ResponseType)90 Parameters (org.testng.annotations.Parameters)89 AuthorizationRequest (org.gluu.oxauth.client.AuthorizationRequest)86 RegisterClient (org.gluu.oxauth.client.RegisterClient)83 RegisterRequest (org.gluu.oxauth.client.RegisterRequest)83 AuthorizeClient (org.gluu.oxauth.client.AuthorizeClient)53 UserInfoClient (org.gluu.oxauth.client.UserInfoClient)49 UserInfoResponse (org.gluu.oxauth.client.UserInfoResponse)49 JwtAuthorizationRequest (org.gluu.oxauth.client.model.authorize.JwtAuthorizationRequest)40 OxAuthCryptoProvider (org.gluu.oxauth.model.crypto.OxAuthCryptoProvider)25 TokenClient (org.gluu.oxauth.client.TokenClient)24 TokenResponse (org.gluu.oxauth.client.TokenResponse)24 Claim (org.gluu.oxauth.client.model.authorize.Claim)24