Java Code Examples for org.gluu.oxauth.model.common.GrantType

The following examples show how to use org.gluu.oxauth.model.common.GrantType. These examples are extracted from open source projects. 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 Project: oxAuth   Source File: TokenRestWebServiceEmbeddedTest.java    License: MIT License 7 votes vote down vote up
@Parameters({"tokenPath", "userId", "userSecret", "audience"})
@Test
public void requestAccessTokenWithClientSecretJwtFail(final String tokenPath, final String userId,
                                                      final String userSecret, final String audience) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();
    request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

    TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);
    tokenRequest.setScope("email read_stream manage_pages");

    tokenRequest.setAuthPassword("INVALID_SECRET");
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
    tokenRequest.setAudience(audience);

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("requestAccessTokenWithClientSecretJwt Fail", response, entity);

    assertEquals(response.getStatus(), 401, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 2
Source Project: oxd   Source File: RegisterSiteTest.java    License: Apache License 2.0 6 votes vote down vote up
public static RegisterSiteResponse registerSite(ClientInterface client, String opHost, String redirectUrls, String idTokenSignedResponseAlg) {

        final RegisterSiteParams params = new RegisterSiteParams();
        params.setOpHost(opHost);
        params.setRedirectUris(Lists.newArrayList(redirectUrls.split(" ")));
        params.setScope(Lists.newArrayList("openid", "uma_protection", "profile", "oxd"));
        params.setResponseTypes(Lists.newArrayList("code", "id_token", "token"));
        params.setIdTokenSignedResponseAlg(idTokenSignedResponseAlg);
        params.setGrantTypes(Lists.newArrayList(
                GrantType.AUTHORIZATION_CODE.getValue(),
                GrantType.OXAUTH_UMA_TICKET.getValue(),
                GrantType.CLIENT_CREDENTIALS.getValue()));

        final RegisterSiteResponse resp = client.registerSite(params);
        assertNotNull(resp);
        assertTrue(!Strings.isNullOrEmpty(resp.getOxdId()));
        return resp;
    }
 
Example 3
Source Project: oxAuth   Source File: ClientAuthenticationFilterHttpTest.java    License: MIT License 6 votes vote down vote up
@Parameters({"userId", "userSecret"})
@Test(dependsOnMethods = "requestClientRegistrationWithCustomAttributes")
public void requestAccessTokenCustomClientAuth2(final String userId, final String userSecret) throws Exception {
    showTitle("requestAccessTokenCustomClientAuth2");

    String username = userId;
    String password = userSecret;

    TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
    tokenRequest.setUsername(username);
    tokenRequest.setPassword(password);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);
    tokenRequest.addCustomParameter("myCustomAttr1", customAttrValue1);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getEntity(), "The entity is null");
    assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
}
 
Example 4
Source Project: oxAuth   Source File: UmaClient.java    License: MIT License 6 votes vote down vote up
public static Token request(final String tokenUrl, final TokenRequest tokenRequest) throws Exception {
	if (tokenRequest.getGrantType() != GrantType.CLIENT_CREDENTIALS) {
		return null;
	}

    TokenClient tokenClient = new TokenClient(tokenUrl);

    tokenClient.setRequest(tokenRequest);

    TokenResponse response = tokenClient.exec();

    if (response.getStatus() == 200) {
        final String patToken = response.getAccessToken();
        final Integer expiresIn = response.getExpiresIn();
        if (Util.allNotBlank(patToken)) {
            return new Token(null, null, patToken, response.getScope(), expiresIn);
        }
    }

    return null;
}
 
Example 5
Source Project: oxAuth   Source File: RegistrationTest.java    License: MIT License 6 votes vote down vote up
@Parameters({"clientJwksUri"})
@Test
public void registrationFail2(final String clientJwksUri) {
    showTitle("registrationFail2");

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", null);
    registerRequest.setJwksUri(clientJwksUri);
    registerRequest.setGrantTypes(Arrays.asList(GrantType.CIBA));

    registerRequest.setBackchannelTokenDeliveryMode(BackchannelTokenDeliveryMode.PING);
    registerRequest.setBackchannelClientNotificationEndpoint(null); // Missing backchannel_client_notification_endpoint
    registerRequest.setBackchannelAuthenticationRequestSigningAlg(AsymmetricSignatureAlgorithm.RS256);
    registerRequest.setBackchannelUserCodeParameter(true);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse response = registerClient.exec();

    showClient(registerClient);
    assertEquals(response.getStatus(), 400, "Unexpected response code: " + response.getEntity());
    assertNotNull(response.getEntity(), "The entity is null");
    assertNotNull(response.getErrorType(), "The error type is null");
    assertNotNull(response.getErrorDescription(), "The error description is null");
}
 
Example 6
Source Project: oxAuth   Source File: RegistrationTest.java    License: MIT License 6 votes vote down vote up
@Parameters({"clientJwksUri"})
@Test
public void registrationFail3(final String clientJwksUri) {
    showTitle("registration3");

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", null);
    registerRequest.setJwksUri(clientJwksUri);
    registerRequest.setGrantTypes(Arrays.asList(GrantType.CIBA));

    registerRequest.setBackchannelTokenDeliveryMode(BackchannelTokenDeliveryMode.PUSH);
    registerRequest.setBackchannelClientNotificationEndpoint(null); // Missing backchannel_client_notification_endpoint
    registerRequest.setBackchannelAuthenticationRequestSigningAlg(AsymmetricSignatureAlgorithm.RS256);
    registerRequest.setBackchannelUserCodeParameter(true);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse response = registerClient.exec();

    showClient(registerClient);
    assertEquals(response.getStatus(), 400, "Unexpected response code: " + response.getEntity());
    assertNotNull(response.getEntity(), "The entity is null");
    assertNotNull(response.getErrorType(), "The error type is null");
    assertNotNull(response.getErrorDescription(), "The error description is null");
}
 
Example 7
Source Project: oxAuth   Source File: RegistrationTest.java    License: MIT License 6 votes vote down vote up
@Parameters({"backchannelClientNotificationEndpoint"})
@Test
public void registrationFail7(final String backchannelClientNotificationEndpoint) {
    showTitle("registrationFail7");

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", null);
    registerRequest.setJwksUri(null); // Missing jwks_uri
    registerRequest.setGrantTypes(Arrays.asList(GrantType.CIBA));

    registerRequest.setBackchannelTokenDeliveryMode(BackchannelTokenDeliveryMode.POLL);
    registerRequest.setBackchannelClientNotificationEndpoint(backchannelClientNotificationEndpoint);
    registerRequest.setBackchannelAuthenticationRequestSigningAlg(AsymmetricSignatureAlgorithm.RS256);
    registerRequest.setBackchannelUserCodeParameter(true);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse response = registerClient.exec();

    showClient(registerClient);
    assertEquals(response.getStatus(), 400, "Unexpected response code: " + response.getEntity());
    assertNotNull(response.getEntity(), "The entity is null");
    assertNotNull(response.getErrorType(), "The error type is null");
    assertNotNull(response.getErrorDescription(), "The error description is null");
}
 
Example 8
Source Project: oxd   Source File: SetupClientTest.java    License: Apache License 2.0 6 votes vote down vote up
public static RegisterSiteResponse setupClient(ClientInterface client, String opHost, String redirectUrls, String postLogoutRedirectUrls, String logoutUri) {

        final RegisterSiteParams params = new RegisterSiteParams();
        params.setOpHost(opHost);
        params.setRedirectUris(Lists.newArrayList(redirectUrls.split(" ")));
        params.setPostLogoutRedirectUris(Lists.newArrayList(postLogoutRedirectUrls.split(" ")));
        params.setClientFrontchannelLogoutUris(Lists.newArrayList(logoutUri));
        params.setScope(Lists.newArrayList("openid", "uma_protection", "profile", "oxd"));
        params.setGrantTypes(Lists.newArrayList(
                GrantType.AUTHORIZATION_CODE.getValue(),
                GrantType.CLIENT_CREDENTIALS.getValue()));

        final RegisterSiteResponse resp = client.registerSite(params);
        assertResponse(resp);
        return resp;
    }
 
Example 9
Source Project: oxd   Source File: RegisterSiteTest.java    License: Apache License 2.0 6 votes vote down vote up
public static RegisterSiteResponse registerSite(
        ClientInterface client, String opHost, String redirectUrls, List<String> scopes, List<String> responseTypes,
        boolean allowSpontaneousScopes, List<String> spontaneousScopes) {

    final RegisterSiteParams params = new RegisterSiteParams();
    params.setOpHost(opHost);
    params.setRedirectUris(Lists.newArrayList(redirectUrls.split(" ")));
    params.setScope(scopes);
    params.setResponseTypes(responseTypes);
    params.setAllowSpontaneousScopes(true);
    params.setSpontaneousScopes(spontaneousScopes);
    params.setGrantTypes(Lists.newArrayList(
            GrantType.AUTHORIZATION_CODE.getValue(),
            GrantType.OXAUTH_UMA_TICKET.getValue(),
            GrantType.CLIENT_CREDENTIALS.getValue()));

    final RegisterSiteResponse resp = client.registerSite(params);
    assertNotNull(resp);
    assertTrue(!Strings.isNullOrEmpty(resp.getOxdId()));
    return resp;
}
 
Example 10
Source Project: oxAuth   Source File: UmaSpontaneousScopeHttpTest.java    License: MIT License 5 votes vote down vote up
@Test(dependsOnMethods = {"registerPermissions"})
public void successfulRptRequest() throws Exception {
    showTitle("successfulRptRequest");

    UmaTokenResponse response = tokenService.requestRpt(
            "Basic " + encodeCredentials(clientResponse.getClientId(), clientResponse.getClientSecret()),
            GrantType.OXAUTH_UMA_TICKET.getValue(),
            permissionFlowTest.ticket,
            null, null, null, null, null);
    assert_(response);

    this.rpt = response.getAccessToken();
}
 
Example 11
Source Project: oxTrust   Source File: UpdateClientAction.java    License: MIT License 5 votes vote down vote up
public void searchAvailableGrantTypes() {
    if (this.availableGrantTypes != null) {
        selectAddedGrantTypes();
        return;
    }
    List<SelectableEntity<GrantType>> tmpAvailableGrantTypes = new ArrayList<SelectableEntity<GrantType>>();
    tmpAvailableGrantTypes.add(new SelectableEntity<GrantType>(GrantType.AUTHORIZATION_CODE));
    tmpAvailableGrantTypes.add(new SelectableEntity<GrantType>(GrantType.IMPLICIT));
    tmpAvailableGrantTypes.add(new SelectableEntity<GrantType>(GrantType.REFRESH_TOKEN));
    tmpAvailableGrantTypes.add(new SelectableEntity<GrantType>(GrantType.CLIENT_CREDENTIALS));
    tmpAvailableGrantTypes.add(new SelectableEntity<GrantType>(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS));
    tmpAvailableGrantTypes.add(new SelectableEntity<GrantType>(GrantType.OXAUTH_UMA_TICKET));
    this.availableGrantTypes = tmpAvailableGrantTypes;
    selectAddedGrantTypes();
}
 
Example 12
/**
 * Fail 1: Call to Token Endpoint with Auth Method
 * <code>client_secret_basic</code> should fail.
 */
@Parameters({"tokenPath", "userId", "userSecret"})
@Test(dependsOnMethods = "tokenEndpointAuthMethodPrivateKeyJwtStep2")
public void tokenEndpointAuthMethodPrivateKeyJwtFail1(final String tokenPath, final String userId,
                                                      final String userSecret) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();

    TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId5);
    tokenRequest.setAuthPassword(clientSecret5);

    request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());
    request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("tokenEndpointAuthMethodPrivateKeyJwtFail1", response, entity);

    assertEquals(response.getStatus(), 401, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 13
Source Project: oxAuth   Source File: UmaTestUtil.java    License: MIT License 5 votes vote down vote up
public static void assert_(UmaMetadata metadata) {
    assertNotNull(metadata, "Metadata is null");
    assertTrue(ArrayUtils.contains(metadata.getGrantTypesSupported(), GrantType.OXAUTH_UMA_TICKET.getValue()));
    assertNotNull(metadata.getIssuer(), "Issuer isn't correct");
    assertNotNull(metadata.getTokenEndpoint(), "Token endpoint isn't correct");
    assertNotNull(metadata.getIntrospectionEndpoint(), "Introspection endpoint isn't correct");
    assertNotNull(metadata.getResourceRegistrationEndpoint(), "Resource registration endpoint isn't correct");
    assertNotNull(metadata.getPermissionEndpoint(), "Permission registration endpoint isn't correct");
    assertNotNull(metadata.getAuthorizationEndpoint(), "Authorization request endpoint isn't correct");
}
 
Example 14
Source Project: oxAuth   Source File: AuthorizationCodeFlowEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({"tokenPath"})
@Test(dependsOnMethods = {"dynamicClientRegistration", "revokeTokensStep2n3"})
public void revokeTokensStep4(final String tokenPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();

    TokenRequest tokenRequest = new TokenRequest(GrantType.REFRESH_TOKEN);
    tokenRequest.setRefreshToken(refreshToken1);
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);

    request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("revokeTokensStep4", response, entity);

    assertEquals(response.getStatus(), 400, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 15
Source Project: oxAuth   Source File: TokenRestWebServiceEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({"tokenPath"})
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestAccessTokenClientCredentials(final String tokenPath) throws Exception {
    // Testing with valid parameters
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();

    TokenRequest tokenRequest = new TokenRequest(GrantType.CLIENT_CREDENTIALS);
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);

    request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());
    request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("requestAccessTokenClientCredentials", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code.");
    assertTrue(
            response.getHeaderString("Cache-Control") != null
                    && response.getHeaderString("Cache-Control").equals("no-store"),
            "Unexpected result: " + response.getHeaderString("Cache-Control"));
    assertTrue(response.getHeaderString("Pragma") != null && response.getHeaderString("Pragma").equals("no-cache"),
            "Unexpected result: " + response.getHeaderString("Pragma"));
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("access_token"), "Unexpected result: access_token not found");
        assertTrue(jsonObj.has("token_type"), "Unexpected result: token_type not found");
        assertTrue(jsonObj.has("scope"), "Unexpected result: scope not found");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 16
Source Project: oxAuth   Source File: AuthorizationCodeFlowEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({"tokenPath", "redirectUri"})
@Test(dependsOnMethods = {"dynamicClientRegistration", "tokenExpirationStep1"})
public void tokenExpirationStep2(final String tokenPath, final String redirectUri) throws Exception {
    // ...Wait until the authorization code expires...
    System.out.println("Sleeping for 20 seconds .....");
    Thread.sleep(20000);

    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();

    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode3);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);

    request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("tokenExpirationStep2", response, entity);

    assertEquals(response.getStatus(), 400, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 17
Source Project: oxAuth   Source File: ClientSecretBasicTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testEncode2() {
    showTitle("testEncode2");

    String clientId = "a+b";
    String clientSecret = "c+d";
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);

    assertEquals(tokenRequest.getEncodedCredentials(), "YSUyQmI6YyUyQmQ=");
}
 
Example 18
Source Project: oxAuth   Source File: TokenSignaturesHttpTest.java    License: MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void requestAuthorizationIdTokenNone(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("requestAuthorizationIdTokenNone");

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

    // 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.NONE);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200);
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

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

    // 2. Request authorization and receive the authorization code.
    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.getCode());
    assertNotNull(authorizationResponse.getState());
    assertNotNull(authorizationResponse.getScope());
    assertNull(authorizationResponse.getIdToken());

    String scope = authorizationResponse.getScope();
    String authorizationCode = authorizationResponse.getCode();

    // 3. Request access token using the authorization code.
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 200);
    assertNotNull(tokenResponse.getEntity());
    assertNotNull(tokenResponse.getAccessToken());
    assertNotNull(tokenResponse.getExpiresIn());
    assertNotNull(tokenResponse.getTokenType());
    assertNotNull(tokenResponse.getRefreshToken());

    String idToken = tokenResponse.getIdToken();

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

    AbstractCryptoProvider cryptoProvider = createCryptoProviderWithAllowedNone();
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), null,
            null, null, SignatureAlgorithm.NONE);
    assertTrue(validJwt);
}
 
Example 19
Source Project: oxAuth   Source File: AcceptValidAsymmetricIdTokenSignature.java    License: MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "postLogoutRedirectUri", "clientJwksUri"})
@Test
public void acceptValidAsymmetricIdTokenSignatureES256(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String postLogoutRedirectUri, final String clientJwksUri) throws Exception {
    showTitle("OC5:FeatureTest-Accept Valid Asymmetric ID Token Signature es256");

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

    List<GrantType> grantTypes = Arrays.asList(GrantType.AUTHORIZATION_CODE);

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, null,
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.ES256);
    registerRequest.setPostLogoutRedirectUris(StringUtils.spaceSeparatedToList(postLogoutRedirectUri));
    registerRequest.setJwksUri(clientJwksUri);
    registerRequest.setSubjectType(SubjectType.PUBLIC);
    registerRequest.setRequireAuthTime(true);
    registerRequest.setDefaultMaxAge(3600);
    registerRequest.setGrantTypes(grantTypes);

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

    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.ES256, publicKey);
    assertTrue(ecdsaSigner.validate(jwt));
}
 
Example 20
Source Project: oxAuth   Source File: ClientInfoRestWebServiceHttpTest.java    License: MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "sectorIdentifierUri"})
@Test
public void requestClientInfoPasswordFlow(
        final String userId, final String userSecret, final String redirectUris, final String sectorIdentifierUri) throws Exception {
    showTitle("requestClientInfoPasswordFlow");

    List<GrantType> grantTypes = Arrays.asList(
            GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
    );

    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setGrantTypes(grantTypes);

    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
    String username = userId;
    String password = userSecret;
    String scope = "clientinfo";

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    TokenResponse response1 = tokenClient.execResourceOwnerPasswordCredentialsGrant(username, password, scope,
            clientId, clientSecret);

    showClient(tokenClient);
    assertEquals(response1.getStatus(), 200, "Unexpected response code: " + response1.getStatus());
    assertNotNull(response1.getEntity(), "The entity is null");
    assertNotNull(response1.getAccessToken(), "The access token is null");
    assertNotNull(response1.getTokenType(), "The token type is null");
    assertNotNull(response1.getScope(), "The scope is null");

    String accessToken = response1.getAccessToken();

    // 3. Request client info
    ClientInfoClient clientInfoClient = new ClientInfoClient(clientInfoEndpoint);
    ClientInfoResponse response2 = clientInfoClient.execClientInfo(accessToken);

    showClient(clientInfoClient);
    assertEquals(response2.getStatus(), 200, "Unexpected response code: " + response2.getStatus());
    assertNotNull(response2.getClaim("displayName"), "Unexpected result: displayName not found");
    assertNotNull(response2.getClaim("inum"), "Unexpected result: inum not found");
    assertNotNull(response2.getClaim("oxAuthAppType"), "Unexpected result: oxAuthAppType not found");
    assertNotNull(response2.getClaim("oxAuthIdTokenSignedResponseAlg"), "Unexpected result: oxAuthIdTokenSignedResponseAlg not found");
    assertNotNull(response2.getClaim("oxAuthRedirectURI"), "Unexpected result: oxAuthRedirectURI not found");
    assertNotNull(response2.getClaim("oxAuthScope"), "Unexpected result: oxAuthScope not found");
}
 
Example 21
Source Project: oxAuth   Source File: TokenRestWebServiceHttpTest.java    License: MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void requestAccessTokenWithClientSecretJwtHS256(
        final String redirectUris, final String userId, final String userSecret, final String dnName,
        final String keyStoreFile, final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
    showTitle("requestAccessTokenWithClientSecretJwtHS256");

    List<GrantType> grantTypes = Arrays.asList(
            GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
    );

    // Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setGrantTypes(grantTypes);

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

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

    TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setAudience(tokenEndpoint);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setRequest(tokenRequest);
    TokenResponse response1 = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(response1.getStatus(), 200, "Unexpected response code: " + response1.getStatus());
    assertNotNull(response1.getEntity(), "The entity is null");
    assertNotNull(response1.getAccessToken(), "The access token is null");
    assertNotNull(response1.getTokenType(), "The token type is null");
}
 
Example 22
Source Project: oxAuth   Source File: TokenRestWebServiceHttpTest.java    License: MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "clientJwksUri", "RS256_keyId", "dnName", "keyStoreFile",
        "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void requestAccessTokenWithClientSecretJwtRS256(
        final String userId, final String userSecret, final String redirectUris, final String jwksUri,
        final String keyId, final String dnName, final String keyStoreFile, final String keyStoreSecret,
        final String sectorIdentifierUri) throws Exception {
    showTitle("requestAccessTokenWithClientSecretJwtRS256");

    List<GrantType> grantTypes = Arrays.asList(
            GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
    );

    // 1. Dynamic Client Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setJwksUri(jwksUri);
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setGrantTypes(grantTypes);

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

    TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);

    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.RS256);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setKeyId(keyId);
    tokenRequest.setAudience(tokenEndpoint);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getEntity(), "The entity is null");
    assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
}
 
Example 23
Source Project: oxAuth   Source File: TokenEncryptionHttpTest.java    License: MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "sectorIdentifierUri"})
//@Test // Before run this test, set openidScopeBackwardCompatibility to true
@Deprecated
public void requestIdTokenAlgA256KWEncA256GCM(
        final String userId, final String userSecret, final String redirectUris, final String sectorIdentifierUri) {
    try {
        showTitle("requestIdTokenAlgA256KWEncA256GCM");

        List<GrantType> grantTypes = Arrays.asList(
                GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
        );

        // 1. Dynamic Client Registration
        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                StringUtils.spaceSeparatedToList(redirectUris));
        registerRequest.setIdTokenEncryptedResponseAlg(KeyEncryptionAlgorithm.A256KW);
        registerRequest.setIdTokenEncryptedResponseEnc(BlockEncryptionAlgorithm.A256GCM);
        registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
        registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
        registerRequest.setGrantTypes(grantTypes);

        RegisterClient registerClient = new RegisterClient(registrationEndpoint);
        registerClient.setRequest(registerRequest);
        RegisterResponse response = registerClient.exec();

        showClient(registerClient);
        assertEquals(response.getStatus(), 200, "Unexpected response code: " + response.getEntity());
        assertNotNull(response.getClientId());
        assertNotNull(response.getClientSecret());
        assertNotNull(response.getRegistrationAccessToken());
        assertNotNull(response.getClientSecretExpiresAt());

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

        // 2. Request authorization
        TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
        tokenRequest.setUsername(userId);
        tokenRequest.setPassword(userSecret);
        tokenRequest.setScope("openid");
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);

        TokenClient tokenClient = new TokenClient(tokenEndpoint);
        tokenClient.setRequest(tokenRequest);
        TokenResponse tokenResponse = tokenClient.exec();

        showClient(tokenClient);
        assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
        assertNotNull(tokenResponse.getEntity(), "The entity is null");
        assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
        assertNotNull(tokenResponse.getTokenType(), "The token type is null");
        assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
        assertNotNull(tokenResponse.getScope(), "The scope is null");
        assertNotNull(tokenResponse.getIdToken(), "The id token is null");

        String idToken = tokenResponse.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));
        assertNotNull(jwe.getClaims().getClaimAsString(JwtClaimName.OX_OPENID_CONNECT_VERSION));
    } catch (Exception ex) {
        fail(ex.getMessage(), ex);
    }
}
 
Example 24
Source Project: oxAuth   Source File: TokenRestWebServiceHttpTest.java    License: MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "clientJwksUri", "RS512_keyId", "dnName", "keyStoreFile",
        "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void requestAccessTokenWithClientSecretJwtRS512(
        final String userId, final String userSecret, final String redirectUris, final String jwksUri,
        final String keyId, final String dnName, final String keyStoreFile, final String keyStoreSecret,
        final String sectorIdentifierUri) throws Exception {
    showTitle("requestAccessTokenWithClientSecretJwtRS512");

    List<GrantType> grantTypes = Arrays.asList(
            GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
    );

    // 1. Dynamic Client Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setJwksUri(jwksUri);
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setGrantTypes(grantTypes);

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

    TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.RS512);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setKeyId(keyId);
    tokenRequest.setAudience(tokenEndpoint);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getEntity(), "The entity is null");
    assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
}
 
Example 25
Source Project: oxAuth   Source File: ClientAuthenticationByAccessTokenHttpTest.java    License: MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret"})
@Test(dependsOnMethods = "requestClientRegistrationWithCustomAttributes")
public void requestAccessTokenCustomClientAuth1(final String userId, final String userSecret) throws Exception {
    showTitle("requestAccessTokenCustomClientAuth1");

    // 1. Request authorization and receive the authorization code.
    List<ResponseType> responseTypes = Arrays.asList(
            ResponseType.CODE,
            ResponseType.ID_TOKEN);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");

    String state = UUID.randomUUID().toString();
    String nonce = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, REDIRECT_URI, nonce);
    authorizationRequest.setState(state);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);
    authorizationRequest.getPrompts().add(Prompt.NONE);

    AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setExecutor(clientExecutor(true));
    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.getCode(), "The code is null");
    assertNotNull(authorizationResponse.getIdToken(), "The idToken is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");

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

    // 2. 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));

    // 3. Request access token using the authorization code.
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(REDIRECT_URI);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setExecutor(clientExecutor(true));
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getEntity(), "The entity is null");
    assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");

    userAccessToken = tokenResponse.getAccessToken();
}
 
Example 26
Source Project: oxAuth   Source File: TokenRestWebServiceWithRSAlgEmbeddedTest.java    License: MIT License 4 votes vote down vote up
@Parameters({"registerPath", "redirectUris", "clientJwksUri"})
@Test
public void requestAccessTokenWithClientSecretJwtRS256Step1(final String registerPath, final String redirectUris,
                                                            final String jwksUri) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setJwksUri(jwksUri);
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

    List<GrantType> grantTypes = Arrays.asList(
            GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
    );
    registerRequest.setGrantTypes(grantTypes);

    String registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());

    Response response = request.post(Entity.json(registerRequestContent));
    String entity = response.readEntity(String.class);

    showResponse("requestAccessTokenWithClientSecretJwtRS256Step1", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
        assertTrue(jsonObj.has(REGISTRATION_ACCESS_TOKEN.toString()));
        assertTrue(jsonObj.has(REGISTRATION_CLIENT_URI.toString()));
        assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));

        clientId1 = jsonObj.getString(RegisterResponseParam.CLIENT_ID.toString());
        clientSecret1 = jsonObj.getString(CLIENT_SECRET.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 27
Source Project: oxAuth   Source File: TokenRestWebServiceHttpTest.java    License: MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "clientJwksUri", "ES256_keyId", "dnName", "keyStoreFile",
        "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void requestAccessTokenWithClientSecretJwtES256(
        final String userId, final String userSecret, final String redirectUris, final String jwksUri,
        final String keyId, final String dnName, final String keyStoreFile, final String keyStoreSecret,
        final String sectorIdentifierUri) throws Exception {
    showTitle("requestAccessTokenWithClientSecretJwtES256");

    List<GrantType> grantTypes = Arrays.asList(
            GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
    );

    // 1. Dynamic Client Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setJwksUri(jwksUri);
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setGrantTypes(grantTypes);

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

    TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);

    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.ES256);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setKeyId(keyId);
    tokenRequest.setAudience(tokenEndpoint);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setRequest(tokenRequest);
    TokenResponse response1 = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(response1.getStatus(), 200, "Unexpected response code: " + response1.getStatus());
    assertNotNull(response1.getEntity(), "The entity is null");
    assertNotNull(response1.getAccessToken(), "The access token is null");
    assertNotNull(response1.getTokenType(), "The token type is null");
}
 
Example 28
Source Project: oxAuth   Source File: TokenAction.java    License: MIT License 4 votes vote down vote up
public GrantType getGrantType() {
    return grantType;
}
 
Example 29
Source Project: oxAuth   Source File: TokenAction.java    License: MIT License 4 votes vote down vote up
public void setGrantType(GrantType grantType) {
    this.grantType = grantType;
}
 
Example 30
Source Project: oxAuth   Source File: TokenRestWebServiceHttpTest.java    License: MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "clientJwksUri", "ES512_keyId", "dnName", "keyStoreFile",
        "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void requestAccessTokenWithClientSecretJwtES512X509Cert(
        final String userId, final String userSecret, final String redirectUris, final String jwksUri,
        final String keyId, final String dnName, final String keyStoreFile, final String keyStoreSecret,
        final String sectorIdentifierUri) throws Exception {
    showTitle("requestAccessTokenWithClientSecretJwtES512X509Cert");

    List<GrantType> grantTypes = Arrays.asList(
            GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
    );

    // 1. Dynamic Client Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setJwksUri(jwksUri);
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setGrantTypes(grantTypes);

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

    TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);

    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.ES512);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setKeyId(keyId);
    tokenRequest.setAudience(tokenEndpoint);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getEntity(), "The entity is null");
    assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
}