Java Code Examples for org.gluu.oxauth.model.jwt.Jwt#parse()

The following examples show how to use org.gluu.oxauth.model.jwt.Jwt#parse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EncodeClaimsInStateParameter.java    From oxAuth with MIT License 6 votes vote down vote up
@Test
public void jwtStateHS384Test() throws Exception {
    showTitle("jwtStateHS384Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    String sharedKey = "shared_key";

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.HS384, sharedKey, cryptoProvider);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), null,
            null, sharedKey, SignatureAlgorithm.HS384);
    assertTrue(validJwt);
}
 
Example 2
Source File: EncodeClaimsInStateParameter.java    From oxAuth with MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "ES384_keyId"})
@Test
public void jwtStateES384Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStateES384Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.ES384, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.ES384);
    assertTrue(validJwt);
}
 
Example 3
Source File: ValidatorTest.java    From oxd with Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithSingleAudArrayAndNoAzp_shouldBeValid() throws InvalidJwtException {
    //"aud": ["6b578a9b-7513-477a-9a7f-1343b487caf8"],
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6WyI2YjU3OGE5Yi03NTEzLTQ3N2EtOWE3Zi0xMzQzYjQ4N2NhZjgiXSwic3ViIjoicy1fWmlyVnQ3Tk9EZG5XREFVR3JqVDJxVVp3SzZjWFRoYjlxVjk5di10ZyIsImF1dGhfdGltZSI6MTU2ODE4NTMyNywiaXNzIjoiaHR0cHM6Ly9kdW1teS1pc3N1ZXIub3JnIiwiZXhwIjoxOTY4MTg4OTMwLCJpYXQiOjE1NjgxODUzMzAsIm5vbmNlIjoiN3I0NnV0NmVtdTlnaTExZ244MDQ0dW02NDAiLCJveE9wZW5JRENvbm5lY3RWZXJzaW9uIjoib3BlbmlkY29ubmVjdC0xLjAifQ.cP6DGPkYYnzDTHrH04F4Q48cPqH2T4R4RjGJmLr5QGA1pUYOOxvLj8Ak0EqmzV_83Zy0wgvyzFCv0xdi06BguUgnM4u6LL8V0hLzrdHIwJHvz5L5Gqbvs5Vg61CpP409lo0sHUN08zfN_WU3EWXK6JlSvFtE59jWSJWBF5pmLX4");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}
 
Example 4
Source File: ValidatorTest.java    From oxd with Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithAudArrayStringWithOneElement_shouldBeValid() throws InvalidJwtException {
    //"aud": "[\"6b578a9b-7513-477a-9a7f-1343b487caf8\"]",
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6IltcIjZiNTc4YTliLTc1MTMtNDc3YS05YTdmLTEzNDNiNDg3Y2FmOFwiXSIsInN1YiI6InMtX1ppclZ0N05PRGRuV0RBVUdyalQycVVad0s2Y1hUaGI5cVY5OXYtdGciLCJhdXRoX3RpbWUiOjE1NjgxODUzMjcsImlzcyI6Imh0dHBzOi8vZHVtbXktaXNzdWVyLm9yZyIsImV4cCI6MTk2ODE4ODkzMCwiaWF0IjoxNTY4MTg1MzMwLCJub25jZSI6IjdyNDZ1dDZlbXU5Z2kxMWduODA0NHVtNjQwIiwib3hPcGVuSURDb25uZWN0VmVyc2lvbiI6Im9wZW5pZGNvbm5lY3QtMS4wIn0.bFgbYtgt5OA2hdwAXXCwaVMUYprArsGoURJgaA0d-YfsDYu8HU9zVDraDhflSc2Wg9uMv4RAKqEfldDwLIRIocGk5XwjyeOHFAWAlDMeDSPUAWy7d7oNGwPrRNZu37RUT1ncRS9ZAIsOhtJjflUTD0J12DeD-wT_V6Jpv8jn3Mo");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}
 
Example 5
Source File: VerifiesCorrectAtHashWhenImplicitFlowUsed.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void verifiesCorrectAtHashWhenImplicitFlowUsed(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Verifies Correct at hash when Implicit Flow Used");

    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);

    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);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getAccessToken());
    assertNotNull(authorizationResponse.getTokenType());
    assertNotNull(authorizationResponse.getIdToken());
    assertNotNull(authorizationResponse.getState());

    String accessToken = authorizationResponse.getAccessToken();
    String idToken = authorizationResponse.getIdToken();

    // 3. Validate access_token and 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));

    RSAPublicKey publicKey = JwkClient.getRSAPublicKey(
            jwksUri,
            jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);

    assertTrue(rsaSigner.validate(jwt));
    assertTrue(rsaSigner.validateAccessToken(accessToken, jwt));
}
 
Example 6
Source File: UsesAsymmetricIdTokenSignatures.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void usesAsymmetricIdTokenSignaturesES512(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Uses Asymmetric ID Token Signatures ES512");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.ID_TOKEN);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.ES512);
    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.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);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getIdToken());
    assertNotNull(authorizationResponse.getState());

    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(
            jwksUri,
            jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    ECDSASigner ecdsaSigner = new ECDSASigner(SignatureAlgorithm.ES512, publicKey);
    assertTrue(ecdsaSigner.validate(jwt));
}
 
Example 7
Source File: GetTokensByCodeOperation.java    From oxd with Apache License 2.0 4 votes vote down vote up
@Override
public IOpResponse execute(GetTokensByCodeParams params) throws Exception {
    validate(params);

    final Rp rp = getRp();
    OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponse(rp);

    final TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(params.getCode());
    tokenRequest.setRedirectUri(rp.getRedirectUri());
    tokenRequest.setAuthUsername(rp.getClientId());
    tokenRequest.setAuthPassword(rp.getClientSecret());
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);


    final TokenClient tokenClient = getOpClientFactory().createTokenClient(discoveryResponse.getTokenEndpoint());
    tokenClient.setExecutor(getHttpService().getClientExecutor());
    tokenClient.setRequest(tokenRequest);
    final TokenResponse response = tokenClient.exec();

    if (response.getStatus() == 200 || response.getStatus() == 302) { // success or redirect

        if (Strings.isNullOrEmpty(response.getIdToken())) {
            LOG.error("id_token is not returned. Please check: 1) OP log file for error (oxauth.log) 2) whether 'openid' scope is present for 'get_authorization_url' command");
            LOG.error("Entity: " + response.getEntity());
            throw new HttpException(ErrorResponseCode.NO_ID_TOKEN_RETURNED);
        }

        if (Strings.isNullOrEmpty(response.getAccessToken())) {
            LOG.error("access_token is not returned");
            throw new HttpException(ErrorResponseCode.NO_ACCESS_TOKEN_RETURNED);
        }

        final Jwt idToken = Jwt.parse(response.getIdToken());

        final Validator validator = new Validator.Builder()
                .discoveryResponse(discoveryResponse)
                .idToken(idToken)
                .keyService(getKeyService())
                .opClientFactory(getOpClientFactory())
                .oxdServerConfiguration(getConfigurationService().getConfiguration())
                .rp(rp)
                .build();

        validator.validateNonce(getStateService());
        validator.validateIdToken();
        validator.validateAccessToken(response.getAccessToken());

        // persist tokens
        rp.setIdToken(response.getIdToken());
        rp.setAccessToken(response.getAccessToken());
        getRpService().update(rp);
        getStateService().deleteExpiredObjectsByKey(params.getState());

        LOG.trace("Scope: " + response.getScope());

        final GetTokensByCodeResponse opResponse = new GetTokensByCodeResponse();
        opResponse.setAccessToken(response.getAccessToken());
        opResponse.setIdToken(response.getIdToken());
        opResponse.setRefreshToken(response.getRefreshToken());
        opResponse.setExpiresIn(response.getExpiresIn() != null ? response.getExpiresIn() : -1);
        opResponse.setIdTokenClaims(Jackson2.createJsonMapper().readTree(idToken.getClaims().toJsonString()));
        return opResponse;
    } else {
        if (response.getStatus() == 400) {
            throw new HttpException(ErrorResponseCode.BAD_REQUEST_INVALID_CODE);
        }
        LOG.error("Failed to get tokens because response code is: " + response.getScope());
    }
    return null;
}
 
Example 8
Source File: UsesSymmetricIdTokenSignatures.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void usesSymmetricIdTokenSignaturesHS256(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Uses Symmetric ID Token Signatures HS256");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.ID_TOKEN);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.HS256);
    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.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);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getIdToken());
    assertNotNull(authorizationResponse.getState());

    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    HMACSigner hmacSigner = new HMACSigner(SignatureAlgorithm.HS256, clientSecret);
    assertTrue(hmacSigner.validate(jwt));
}
 
Example 9
Source File: TokenSignaturesHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void requestAuthorizationIdTokenPS256(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("requestAuthorizationIdTokenPS256");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.ID_TOKEN);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setContacts(Arrays.asList("[email protected]", "[email protected]"));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.PS256);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
    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.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);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);
    authorizationRequest.getPrompts().add(Prompt.NONE);

    AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setRequest(authorizationRequest);
    AuthorizationResponse authorizationResponse = authorizeClient.exec();

    showClient(authorizeClient);
    assertEquals(authorizationResponse.getStatus(), 302, "Unexpected response code: " + authorizationResponse.getStatus());
    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getIdToken(), "The idToken is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");

    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    String keyId = jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);
    JwkClient jwkClient = new JwkClient(jwksUri);
    JwkResponse jwkResponse = jwkClient.exec();

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            jwkResponse.getJwks().toJSONObject(), null, SignatureAlgorithm.PS256);
    assertTrue(validJwt);
}
 
Example 10
Source File: TokenSignaturesHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void requestAuthorizationIdTokenES512(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("requestAuthorizationIdTokenES512");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.ID_TOKEN);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setContacts(Arrays.asList("[email protected]", "[email protected]"));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.ES512);
    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.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);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getIdToken(), "The idToken is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");

    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    String keyId = jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);
    JwkClient jwkClient = new JwkClient(jwksUri);
    JwkResponse jwkResponse = jwkClient.exec();

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            jwkResponse.getJwks().toJSONObject(), null, SignatureAlgorithm.ES512);
    assertTrue(validJwt);
}
 
Example 11
Source File: VerifiesCorrectCHashWhenCodeFlowUsed.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void verifiesCorrectCHashWhenCodeFlowUsed(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Verifies Correct c hash when Code Flow Used");

    List<ResponseType> responseTypes = Arrays.asList(
            ResponseType.CODE,
            ResponseType.ID_TOKEN);

    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    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 state = UUID.randomUUID().toString();
    String nonce = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getCode(), "The code is null");
    assertNotNull(authorizationResponse.getIdToken(), "The idToken is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");

    String code = authorizationResponse.getCode();
    String idToken = authorizationResponse.getIdToken();

    // 3. Validate code and 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.CODE_HASH));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME));

    RSAPublicKey publicKey = JwkClient.getRSAPublicKey(
            jwksUri,
            jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);

    assertTrue(rsaSigner.validate(jwt));
    assertTrue(rsaSigner.validateAuthorizationCode(code, jwt));
}
 
Example 12
Source File: CanRequestAndUseClaimsInIdToken.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "dnName", "keyStoreFile", "keyStoreSecret",
        "sectorIdentifierUri"})
@Test
public void canRequestAndUseClaimsInIdToken(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String dnName, final String keyStoreFile, final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Can Request and Use Claims in id token");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.HS256);
    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.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    // 2. Request Authorization
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    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);

    JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest, SignatureAlgorithm.HS256, clientSecret, cryptoProvider);
    jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.NAME, ClaimValue.createEssential(true)));
    jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
    String authJwt = jwtAuthorizationRequest.getEncodedJwt();
    authorizationRequest.setRequest(authJwt);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getIdToken());
    assertNotNull(authorizationResponse.getState());

    String idToken = authorizationResponse.getIdToken();

    // 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().getClaimAsString(JwtClaimName.NAME));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EMAIL));

    HMACSigner hmacSigner = new HMACSigner(SignatureAlgorithm.HS256, clientSecret);
    assertTrue(hmacSigner.validate(jwt));
}
 
Example 13
Source File: UsesAsymmetricIdTokenSignatures.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void usesAsymmetricIdTokenSignaturesRS384(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Uses Asymmetric ID Token Signatures RS384");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.ID_TOKEN);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.RS384);
    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.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);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getIdToken());
    assertNotNull(authorizationResponse.getState());

    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    RSAPublicKey publicKey = JwkClient.getRSAPublicKey(
            jwksUri,
            jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS384, publicKey);
    assertTrue(rsaSigner.validate(jwt));
}
 
Example 14
Source File: EncodeClaimsInStateParameter.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void encodeClaimsInStateParameterHS384(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("encodeClaimsInStateParameterHS384");

    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);

    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
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();

    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();
    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.HS384, clientSecret, cryptoProvider);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
    String encodedState = jwtState.getEncodedJwt();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(encodedState);

    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 state = authorizationResponse.getState();

    // 3. Validate state
    Jwt jwt = Jwt.parse(state);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), null,
            null, clientSecret, SignatureAlgorithm.HS384);
    assertTrue(validJwt);
}
 
Example 15
Source File: UsesAsymmetricIdTokenSignatures.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void usesAsymmetricIdTokenSignaturesRS512(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Uses Asymmetric ID Token Signatures RS512");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.ID_TOKEN);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.RS512);
    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.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);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getIdToken());
    assertNotNull(authorizationResponse.getState());

    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    RSAPublicKey publicKey = JwkClient.getRSAPublicKey(
            jwksUri,
            jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS512, publicKey);
    assertTrue(rsaSigner.validate(jwt));
}
 
Example 16
Source File: EncodeClaimsInStateParameter.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri",
        "keyStoreFile", "keyStoreSecret", "dnName", "PS512_keyId"})
@Test
public void encodeClaimsInStateParameterPS512(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri, final String keyStoreFile, final String keyStoreSecret,
        final String dnName, final String keyId) throws Exception {
    showTitle("encodeClaimsInStateParameterPS512");

    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);

    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", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();
    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.PS512, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
    String encodedState = jwtState.getEncodedJwt();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(encodedState);

    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 state = authorizationResponse.getState();

    // 3. Validate state
    Jwt jwt = Jwt.parse(state);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.PS512);
    assertTrue(validJwt);
}
 
Example 17
Source File: TokenSignaturesHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void requestAuthorizationIdTokenHS256(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("requestAuthorizationIdTokenHS256");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.ID_TOKEN);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setContacts(Arrays.asList("[email protected]", "[email protected]"));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.HS256);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
    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.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);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);
    authorizationRequest.getPrompts().add(Prompt.NONE);

    AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setRequest(authorizationRequest);
    AuthorizationResponse authorizationResponse = authorizeClient.exec();

    showClient(authorizeClient);
    assertEquals(authorizationResponse.getStatus(), 302, "Unexpected response code: " + authorizationResponse.getStatus());
    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getIdToken(), "The idToken is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");

    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), null,
            null, clientSecret, SignatureAlgorithm.HS256);
    assertTrue(validJwt);
}
 
Example 18
Source File: RejectInvalidSymmetricIdTokenSignature.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void rejectInvalidSymmetricIdTokenSignature(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Reject Invalid Symmetric ID Token Signature");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.ID_TOKEN);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.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.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);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getIdToken());
    assertNotNull(authorizationResponse.getState());

    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    HMACSigner hmacSigner = new HMACSigner(SignatureAlgorithm.HS256, clientSecret);
    assertFalse(hmacSigner.validate(jwt));
}
 
Example 19
Source File: UsesAsymmetricIdTokenSignatures.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void usesAsymmetricIdTokenSignaturesES384(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Uses Asymmetric ID Token Signatures ES384");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.ID_TOKEN);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.ES384);
    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.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);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getIdToken());
    assertNotNull(authorizationResponse.getState());

    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(
            jwksUri,
            jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    ECDSASigner ecdsaSigner = new ECDSASigner(SignatureAlgorithm.ES384, publicKey);
    assertTrue(ecdsaSigner.validate(jwt));
}
 
Example 20
Source File: EncodeClaimsInStateParameter.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri",
        "keyStoreFile", "keyStoreSecret", "dnName", "ES256_keyId"})
@Test
public void encodeClaimsInStateParameterES256(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri, final String keyStoreFile, final String keyStoreSecret,
        final String dnName, final String keyId) throws Exception {
    showTitle("encodeClaimsInStateParameterES256");

    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);

    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", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();
    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.ES256, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
    String encodedState = jwtState.getEncodedJwt();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(encodedState);

    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 state = authorizationResponse.getState();

    // 3. Validate state
    Jwt jwt = Jwt.parse(state);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.ES256);
    assertTrue(validJwt);
}