Search in sources :

Example 11 with Jwe

use of org.xdi.oxauth.model.jwe.Jwe in project oxAuth by GluuFederation.

the class CanRequestAndUseEncryptedIdTokenResponse method canRequestAndUseEncryptedIdTokenResponse.

@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "sectorIdentifierUri" })
@Test
public void canRequestAndUseEncryptedIdTokenResponse(final String userId, final String userSecret, final String redirectUri, final String redirectUris, final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Can Request and Use Encrypted ID Token Response");
    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.setIdTokenEncryptedResponseAlg(KeyEncryptionAlgorithm.A128KW);
    registerRequest.setIdTokenEncryptedResponseEnc(BlockEncryptionAlgorithm.A128GCM);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    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();
    String clientSecret = registerResponse.getClientSecret();
    // 2. Request authorization
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    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();
    // 3. Read Encrypted ID Token
    Jwe jwe = Jwe.parse(idToken, null, clientSecret.getBytes(Util.UTF8_STRING_ENCODING));
    assertNotNull(jwe.getHeader().getClaimAsString(JwtHeaderName.TYPE));
    assertNotNull(jwe.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
    assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.ISSUER));
    assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
    assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
    assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
    assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
}
Also used : Jwe(org.xdi.oxauth.model.jwe.Jwe) ResponseType(org.xdi.oxauth.model.common.ResponseType) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(org.xdi.oxauth.BaseTest)

Example 12 with Jwe

use of org.xdi.oxauth.model.jwe.Jwe in project oxAuth by GluuFederation.

the class IdTokenFactory method generateEncryptedIdToken.

public Jwe generateEncryptedIdToken(IAuthorizationGrant authorizationGrant, String nonce, AuthorizationCode authorizationCode, AccessToken accessToken, Set<String> scopes, boolean includeIdTokenClaims) throws Exception {
    Jwe jwe = new Jwe();
    // Header
    KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getIdTokenEncryptedResponseAlg());
    BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getIdTokenEncryptedResponseEnc());
    jwe.getHeader().setType(JwtType.JWT);
    jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
    jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
    // Claims
    jwe.getClaims().setIssuer(appConfiguration.getIssuer());
    jwe.getClaims().setAudience(authorizationGrant.getClient().getClientId());
    int lifeTime = appConfiguration.getIdTokenLifetime();
    Calendar calendar = Calendar.getInstance();
    Date issuedAt = calendar.getTime();
    calendar.add(Calendar.SECOND, lifeTime);
    Date expiration = calendar.getTime();
    jwe.getClaims().setExpirationTime(expiration);
    jwe.getClaims().setIssuedAt(issuedAt);
    if (authorizationGrant.getAcrValues() != null) {
        jwe.getClaims().setClaim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, authorizationGrant.getAcrValues());
        setAmrClaim(jwe, authorizationGrant.getAcrValues());
    }
    if (StringUtils.isNotBlank(nonce)) {
        jwe.getClaims().setClaim(JwtClaimName.NONCE, nonce);
    }
    if (authorizationGrant.getAuthenticationTime() != null) {
        jwe.getClaims().setClaim(JwtClaimName.AUTHENTICATION_TIME, authorizationGrant.getAuthenticationTime());
    }
    if (authorizationCode != null) {
        String codeHash = authorizationCode.getHash(null);
        jwe.getClaims().setClaim(JwtClaimName.CODE_HASH, codeHash);
    }
    if (accessToken != null) {
        String accessTokenHash = accessToken.getHash(null);
        jwe.getClaims().setClaim(JwtClaimName.ACCESS_TOKEN_HASH, accessTokenHash);
    }
    jwe.getClaims().setClaim(JwtClaimName.OX_OPENID_CONNECT_VERSION, appConfiguration.getOxOpenIdConnectVersion());
    List<org.xdi.oxauth.model.common.Scope> dynamicScopes = Lists.newArrayList();
    if (includeIdTokenClaims) {
        for (String scopeName : scopes) {
            org.xdi.oxauth.model.common.Scope scope = scopeService.getScopeByDisplayName(scopeName);
            if (org.xdi.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType()) {
                dynamicScopes.add(scope);
                continue;
            }
            if (scope != null && scope.getOxAuthClaims() != null) {
                for (String claimDn : scope.getOxAuthClaims()) {
                    GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn);
                    String claimName = gluuAttribute.getOxAuthClaimName();
                    String ldapName = gluuAttribute.getName();
                    String attributeValue;
                    if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) {
                        if (ldapName.equals("uid")) {
                            attributeValue = authorizationGrant.getUser().getUserId();
                        } else {
                            attributeValue = authorizationGrant.getUser().getAttribute(gluuAttribute.getName());
                        }
                        jwe.getClaims().setClaim(claimName, attributeValue);
                    }
                }
            }
        }
    }
    if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember() != null) {
        for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember().getClaims()) {
            // ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType());
            boolean optional = true;
            GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName());
            if (gluuAttribute != null) {
                String ldapClaimName = gluuAttribute.getName();
                Object attribute = authorizationGrant.getUser().getAttribute(ldapClaimName, optional);
                if (attribute != null) {
                    if (attribute instanceof JSONArray) {
                        JSONArray jsonArray = (JSONArray) attribute;
                        List<String> values = new ArrayList<String>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            String value = jsonArray.optString(i);
                            if (value != null) {
                                values.add(value);
                            }
                        }
                        jwe.getClaims().setClaim(claim.getName(), values);
                    } else {
                        String value = (String) attribute;
                        jwe.getClaims().setClaim(claim.getName(), value);
                    }
                }
            }
        }
    }
    // Check for Subject Identifier Type
    if (authorizationGrant.getClient().getSubjectType() != null && SubjectType.fromString(authorizationGrant.getClient().getSubjectType()).equals(SubjectType.PAIRWISE)) {
        String sectorIdentifierUri;
        if (StringUtils.isNotBlank(authorizationGrant.getClient().getSectorIdentifierUri())) {
            sectorIdentifierUri = authorizationGrant.getClient().getSectorIdentifierUri();
        } else {
            sectorIdentifierUri = authorizationGrant.getClient().getRedirectUris()[0];
        }
        String userInum = authorizationGrant.getUser().getAttribute("inum");
        PairwiseIdentifier pairwiseIdentifier = pairwiseIdentifierService.findPairWiseIdentifier(userInum, sectorIdentifierUri);
        if (pairwiseIdentifier == null) {
            pairwiseIdentifier = new PairwiseIdentifier(sectorIdentifierUri);
            pairwiseIdentifier.setId(UUID.randomUUID().toString());
            pairwiseIdentifier.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier(pairwiseIdentifier.getId(), userInum));
            pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseIdentifier);
        }
        jwe.getClaims().setSubjectIdentifier(pairwiseIdentifier.getId());
    } else {
        String openidSubAttribute = appConfiguration.getOpenidSubAttribute();
        if (openidSubAttribute.equals("uid")) {
            jwe.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getUserId());
        } else {
            jwe.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute(openidSubAttribute));
        }
    }
    if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) {
        final UnmodifiableAuthorizationGrant unmodifiableAuthorizationGrant = new UnmodifiableAuthorizationGrant(authorizationGrant);
        DynamicScopeExternalContext dynamicScopeContext = new DynamicScopeExternalContext(dynamicScopes, jwe, unmodifiableAuthorizationGrant);
        externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopeContext);
    }
    // Encryption
    if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5) {
        JSONObject jsonWebKeys = JwtUtil.getJSONWebKeys(authorizationGrant.getClient().getJwksUri());
        AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(appConfiguration);
        String keyId = cryptoProvider.getKeyId(JSONWebKeySet.fromJSONObject(jsonWebKeys), SignatureAlgorithm.RS256);
        PublicKey publicKey = cryptoProvider.getPublicKey(keyId, jsonWebKeys);
        if (publicKey != null) {
            JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, publicKey);
            jwe = jweEncrypter.encrypt(jwe);
        } else {
            throw new InvalidJweException("The public key is not valid");
        }
    } else if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
        try {
            byte[] sharedSymmetricKey = clientService.decryptSecret(authorizationGrant.getClient().getClientSecret()).getBytes(Util.UTF8_STRING_ENCODING);
            JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, sharedSymmetricKey);
            jwe = jweEncrypter.encrypt(jwe);
        } catch (UnsupportedEncodingException e) {
            throw new InvalidJweException(e);
        } catch (StringEncrypter.EncryptionException e) {
            throw new InvalidJweException(e);
        } catch (Exception e) {
            throw new InvalidJweException(e);
        }
    }
    return jwe;
}
Also used : BlockEncryptionAlgorithm(org.xdi.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm) PairwiseIdentifier(org.xdi.oxauth.model.ldap.PairwiseIdentifier) org.xdi.oxauth.model.common(org.xdi.oxauth.model.common) Jwe(org.xdi.oxauth.model.jwe.Jwe) AbstractCryptoProvider(org.xdi.oxauth.model.crypto.AbstractCryptoProvider) JweEncrypter(org.xdi.oxauth.model.jwe.JweEncrypter) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) PublicKey(java.security.PublicKey) JSONArray(org.codehaus.jettison.json.JSONArray) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DynamicScopeExternalContext(org.xdi.oxauth.service.external.context.DynamicScopeExternalContext) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GluuAttribute(org.xdi.model.GluuAttribute) JSONObject(org.codehaus.jettison.json.JSONObject) KeyEncryptionAlgorithm(org.xdi.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) JwtSubClaimObject(org.xdi.oxauth.model.jwt.JwtSubClaimObject) JSONObject(org.codehaus.jettison.json.JSONObject) JweEncrypterImpl(org.xdi.oxauth.model.jwe.JweEncrypterImpl) Claim(org.xdi.oxauth.model.authorize.Claim)

Example 13 with Jwe

use of org.xdi.oxauth.model.jwe.Jwe in project oxAuth by GluuFederation.

the class CanProvideEncryptedIdTokenResponse method canProvideEncryptedIdTokenResponseAlgRSA15EncA256CBCPLUSHS512.

@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "clientJwksUri", "RS256_keyId", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri" })
@Test
public void canProvideEncryptedIdTokenResponseAlgRSA15EncA256CBCPLUSHS512(final String userId, final String userSecret, final String redirectUri, final String redirectUris, final String jwksUri, final String keyId, final String keyStoreFile, final String keyStoreSecret, final String sectorIdentifierUri) {
    try {
        showTitle("OC5:FeatureTest-Can Provide Encrypted ID Token Response RSA1_5 A256CBC_PLUS_HS512");
        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.setJwksUri(jwksUri);
        registerRequest.setIdTokenEncryptedResponseAlg(KeyEncryptionAlgorithm.RSA1_5);
        registerRequest.setIdTokenEncryptedResponseEnc(BlockEncryptionAlgorithm.A256CBC_PLUS_HS512);
        registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
        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", "profile", "address", "email");
        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();
        // 3. Read Encrypted ID Token
        OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, null);
        PrivateKey privateKey = cryptoProvider.getPrivateKey(keyId);
        Jwe jwe = Jwe.parse(idToken, privateKey, null);
        assertNotNull(jwe.getHeader().getClaimAsString(JwtHeaderName.TYPE));
        assertNotNull(jwe.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.ISSUER));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
    } catch (Exception ex) {
        fail(ex.getMessage(), ex);
    }
}
Also used : PrivateKey(java.security.PrivateKey) ResponseType(org.xdi.oxauth.model.common.ResponseType) OxAuthCryptoProvider(org.xdi.oxauth.model.crypto.OxAuthCryptoProvider) Jwe(org.xdi.oxauth.model.jwe.Jwe) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(org.xdi.oxauth.BaseTest)

Example 14 with Jwe

use of org.xdi.oxauth.model.jwe.Jwe in project oxAuth by GluuFederation.

the class UserInfoClient method exec.

/**
     * Executes the call to the REST Service and processes the response.
     *
     * @return The service response.
     */
public UserInfoResponse exec() {
    // Prepare request parameters
    initClientRequest();
    clientRequest.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    clientRequest.setHttpMethod(getHttpMethod());
    if (getRequest().getAuthorizationMethod() == null || getRequest().getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD) {
        if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
            clientRequest.header("Authorization", "Bearer " + getRequest().getAccessToken());
        }
    } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
        if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
            clientRequest.formParameter("access_token", getRequest().getAccessToken());
        }
    } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
        if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
            clientRequest.queryParameter("access_token", getRequest().getAccessToken());
        }
    }
    // Call REST Service and handle response
    try {
        if (getRequest().getAuthorizationMethod() == null || getRequest().getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD || getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
            clientResponse = clientRequest.get(String.class);
        } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
            clientResponse = clientRequest.post(String.class);
        }
        int status = clientResponse.getStatus();
        setResponse(new UserInfoResponse(status));
        String entity = clientResponse.getEntity(String.class);
        getResponse().setEntity(entity);
        getResponse().setHeaders(clientResponse.getMetadata());
        if (StringUtils.isNotBlank(entity)) {
            List<Object> contentType = clientResponse.getHeaders().get("Content-Type");
            if (contentType != null && contentType.contains("application/jwt")) {
                String[] jwtParts = entity.split("\\.");
                if (jwtParts.length == 5) {
                    byte[] sharedSymmetricKey = sharedKey != null ? sharedKey.getBytes(Util.UTF8_STRING_ENCODING) : null;
                    Jwe jwe = Jwe.parse(entity, privateKey, sharedSymmetricKey);
                    getResponse().setClaims(jwe.getClaims().toMap());
                } else {
                    Jwt jwt = Jwt.parse(entity);
                    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
                    boolean signatureVerified = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), jwt.getHeader().getKeyId(), JwtUtil.getJSONWebKeys(jwksUri), sharedKey, jwt.getHeader().getAlgorithm());
                    if (signatureVerified) {
                        getResponse().setClaims(jwt.getClaims().toMap());
                    }
                }
            } else {
                try {
                    JSONObject jsonObj = new JSONObject(entity);
                    if (jsonObj.has("error")) {
                        getResponse().setErrorType(UserInfoErrorResponseType.fromString(jsonObj.getString("error")));
                        jsonObj.remove("error");
                    }
                    if (jsonObj.has("error_description")) {
                        getResponse().setErrorDescription(jsonObj.getString("error_description"));
                        jsonObj.remove("error_description");
                    }
                    if (jsonObj.has("error_uri")) {
                        getResponse().setErrorUri(jsonObj.getString("error_uri"));
                        jsonObj.remove("error_uri");
                    }
                    for (Iterator<String> iterator = jsonObj.keys(); iterator.hasNext(); ) {
                        String key = iterator.next();
                        List<String> values = new ArrayList<String>();
                        JSONArray jsonArray = jsonObj.optJSONArray(key);
                        if (jsonArray != null) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                String value = jsonArray.optString(i);
                                if (value != null) {
                                    values.add(value);
                                }
                            }
                        } else {
                            String value = jsonObj.optString(key);
                            if (value != null) {
                                values.add(value);
                            }
                        }
                        getResponse().getClaims().put(key, values);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        closeConnection();
    }
    return getResponse();
}
Also used : Jwt(org.xdi.oxauth.model.jwt.Jwt) ArrayList(java.util.ArrayList) JSONArray(org.codehaus.jettison.json.JSONArray) JSONException(org.codehaus.jettison.json.JSONException) JSONException(org.codehaus.jettison.json.JSONException) OxAuthCryptoProvider(org.xdi.oxauth.model.crypto.OxAuthCryptoProvider) JSONObject(org.codehaus.jettison.json.JSONObject) Jwe(org.xdi.oxauth.model.jwe.Jwe) JSONObject(org.codehaus.jettison.json.JSONObject)

Example 15 with Jwe

use of org.xdi.oxauth.model.jwe.Jwe in project oxAuth by GluuFederation.

the class CanProvideEncryptedIdTokenResponse method canProvideEncryptedIdTokenResponseAlgA256KWEncA256GCM.

@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "sectorIdentifierUri" })
@Test
public void canProvideEncryptedIdTokenResponseAlgA256KWEncA256GCM(final String userId, final String userSecret, final String redirectUri, final String redirectUris, final String sectorIdentifierUri) {
    try {
        showTitle("OC5:FeatureTest-Can Provide Encrypted ID Token Response A256KW A256GCM");
        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.setIdTokenEncryptedResponseAlg(KeyEncryptionAlgorithm.A256KW);
        registerRequest.setIdTokenEncryptedResponseEnc(BlockEncryptionAlgorithm.A256GCM);
        registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
        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();
        String clientSecret = registerResponse.getClientSecret();
        // 2. Request authorization
        List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
        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();
        // 3. Read Encrypted ID Token
        Jwe jwe = Jwe.parse(idToken, null, clientSecret.getBytes(Util.UTF8_STRING_ENCODING));
        assertNotNull(jwe.getHeader().getClaimAsString(JwtHeaderName.TYPE));
        assertNotNull(jwe.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.ISSUER));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
    } catch (Exception ex) {
        fail(ex.getMessage(), ex);
    }
}
Also used : Jwe(org.xdi.oxauth.model.jwe.Jwe) ResponseType(org.xdi.oxauth.model.common.ResponseType) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(org.xdi.oxauth.BaseTest)

Aggregations

Jwe (org.xdi.oxauth.model.jwe.Jwe)24 Test (org.testng.annotations.Test)21 BaseTest (org.xdi.oxauth.BaseTest)21 Parameters (org.testng.annotations.Parameters)19 JSONObject (org.codehaus.jettison.json.JSONObject)13 OxAuthCryptoProvider (org.xdi.oxauth.model.crypto.OxAuthCryptoProvider)13 PrivateKey (java.security.PrivateKey)12 ResponseType (org.xdi.oxauth.model.common.ResponseType)11 JwtState (org.xdi.oxauth.client.model.JwtState)10 JSONArray (org.codehaus.jettison.json.JSONArray)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 PublicKey (java.security.PublicKey)2 GluuAttribute (org.xdi.model.GluuAttribute)2 Claim (org.xdi.oxauth.model.authorize.Claim)2 AbstractCryptoProvider (org.xdi.oxauth.model.crypto.AbstractCryptoProvider)2 InvalidJweException (org.xdi.oxauth.model.exception.InvalidJweException)2 JweEncrypter (org.xdi.oxauth.model.jwe.JweEncrypter)2 JweEncrypterImpl (org.xdi.oxauth.model.jwe.JweEncrypterImpl)2 JwtSubClaimObject (org.xdi.oxauth.model.jwt.JwtSubClaimObject)2 PairwiseIdentifier (org.xdi.oxauth.model.ldap.PairwiseIdentifier)2