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

The following examples show how to use org.gluu.oxauth.model.common.GrantType#AUTHORIZATION_CODE . 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: ClientSecretBasicTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void testEncode1() {
    showTitle("testEncode1");

    String clientId = "Aladdin";
    String clientSecret = "open sesame";
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);

    assertEquals(tokenRequest.getEncodedCredentials(), "QWxhZGRpbjpvcGVuK3Nlc2FtZQ==");
}
 
Example 2
Source File: ClientSecretBasicTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void testEncode3() {
    showTitle("testEncode3");

    String clientId = "@!12AD!0008!6D30.23D7";
    String clientSecret = "P@55W0rd!";
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);

    assertEquals(tokenRequest.getEncodedCredentials(), "JTQwJTIxMTJBRCUyMTAwMDglMjE2RDMwLjIzRDc6UCU0MDU1VzByZCUyMQ==");
}
 
Example 3
Source File: AuthorizationCodeFlowEmbeddedTest.java    From oxAuth with 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 4
Source File: SupportScopeRequestingPhoneClaims.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void supportScopeRequestingPhoneClaims(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Support scope Requesting phone Claims");

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

    // 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
    List<String> scopes = Arrays.asList("openid", "phone");
    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());

    String authorizationCode = authorizationResponse.getCode();

    // 3. Get Access Token
    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, "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");

    String accessToken = tokenResponse.getAccessToken();

    // 4. Request user info
    UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);

    showClient(userInfoClient);
    assertEquals(userInfoResponse.getStatus(), 200, "Unexpected response code: " + userInfoResponse.getStatus());
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
}
 
Example 5
Source File: SupportAuthenticationToTokenEndpointWithSymmetricallySignedJWTs.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "redirectUri", "userId", "userSecret", "sectorIdentifierUri"})
@Test
public void supportAuthenticationToTokenEndpointWithSymmetricallySignedJWTsHS256(
        final String redirectUris, final String redirectUri, final String userId, final String userSecret,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Support Authentication to Token Endpoint with Symmetrically Signed JWTs (HS256)");

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

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

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

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

    // 2. Request authorization
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String state = UUID.randomUUID().toString();

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

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

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

    String authorizationCode = authorizationResponse.getCode();

    // 3. Get Access Token
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();

    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setAudience(tokenEndpoint);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    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.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
}
 
Example 6
Source File: SupportScopeRequestingAllBasicClaims.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void supportScopeRequestingAllBasicClaims(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Support scope Requesting All Basic Claims");

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

    // 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
    List<String> scopes = Arrays.asList("openid", "profile", "email", "address", "phone");
    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());

    String authorizationCode = authorizationResponse.getCode();

    // 3. Get Access Token
    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, "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");

    String accessToken = tokenResponse.getAccessToken();

    // 4. Request user info
    UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);

    showClient(userInfoClient);
    assertEquals(userInfoResponse.getStatus(), 200, "Unexpected response code: " + userInfoResponse.getStatus());
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
}
 
Example 7
Source File: ObtainAccessTokenLoadTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris"})
@Test(invocationCount = 1000, threadPoolSize = 100)
public void obtainAccessToken(final String userId, final String userSecret, String redirectUris) throws Exception {
    showTitle("requestClientAssociate1");

    redirectUris = "https://client.example.com/cb";

    final List<ResponseType> responseTypes = new ArrayList<ResponseType>();
    responseTypes.add(ResponseType.CODE);
    responseTypes.add(ResponseType.ID_TOKEN);

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

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

    // 1. Request authorization and receive the authorization code.

    final List<String> scopes = Arrays.asList("openid", "profile", "address", "email");

    final AuthorizationRequest request = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUris, null);
    request.setState("af0ifjsldkj");
    request.setAuthUsername(userId);
    request.setAuthPassword(userSecret);
    request.getPrompts().add(Prompt.NONE);

    final AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setRequest(request);
    final AuthorizationResponse response1 = authorizeClient.exec();

    ClientUtils.showClient(authorizeClient);

    final String scope = response1.getScope();
    final String authorizationCode = response1.getCode();
    assertTrue(Util.allNotBlank(authorizationCode));


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

    final TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
    tokenClient1.setRequest(tokenRequest);
    final TokenResponse response2 = tokenClient1.exec();
    ClientUtils.showClient(authorizeClient);

    assertTrue(response2.getStatus() == 200);
    final String patToken = response2.getAccessToken();
    final String patRefreshToken = response2.getRefreshToken();
    assertTrue(Util.allNotBlank(patToken, patRefreshToken));
}
 
Example 8
Source File: OPRegistrationJwks.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUri", "postLogoutRedirectUri", "clientJwksUri", "userId", "userSecret", "RS256_keyId",
        "dnName", "keyStoreFile", "keyStoreSecret"})
@Test
public void opRegistrationJwks(
        final String redirectUri, final String postLogoutRedirectUri, final String clientJwksUri,
        final String userId, final String userSecret, final String keyId, final String dnName,
        final String keyStoreFile, final String keyStoreSecret) throws Exception {
    showTitle("opRegistrationJwks");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);
    List<GrantType> grantTypes = Arrays.asList(GrantType.AUTHORIZATION_CODE);
    List<String> contacts = Arrays.asList("[email protected]", "[email protected]");

    // 1. Register client
    JwkClient jwkClient = new JwkClient(clientJwksUri);
    JwkResponse jwkResponse = jwkClient.exec();

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUri));
    registerRequest.setPostLogoutRedirectUris(Arrays.asList(postLogoutRedirectUri));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setGrantTypes(grantTypes);
    registerRequest.setContacts(contacts);
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    registerRequest.setJwks(jwkResponse.getJwks().toString());

    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.getRegistrationClientUri());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());
    assertNotNull(registerResponse.getResponseTypes());
    assertTrue(registerResponse.getResponseTypes().containsAll(responseTypes));
    assertNotNull(registerResponse.getGrantTypes());
    assertTrue(registerResponse.getGrantTypes().containsAll(grantTypes));
    assertNotNull(registerResponse.getClaims().get(RegisterRequestParam.JWKS.getName()));
    assertNotNull(registerResponse.getClaims().get(RegisterRequestParam.TOKEN_ENDPOINT_AUTH_METHOD.getName()));
    assertEquals(AuthenticationMethod.PRIVATE_KEY_JWT.toString(), registerResponse.getClaims().get(RegisterRequestParam.TOKEN_ENDPOINT_AUTH_METHOD.getName()));

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

    // 2. Request authorization
    List<String> scopes = Arrays.asList("openid");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();

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

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

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

    String authorizationCode = authorizationResponse.getCode();

    // 3. Request access token using the authorization code.
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);

    tokenRequest.setRedirectUri(redirectUri);
    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");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
    assertNotNull(tokenResponse.getIdToken(), "The id token is null");
}
 
Example 9
Source File: SupportAuthenticationToTokenEndpointUsingHttpBasicWithPost.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "redirectUri", "userId", "userSecret", "sectorIdentifierUri"})
@Test
public void supportAuthenticationToTokenEndpointUsingHttpBasicWithPost(
        final String redirectUris, final String redirectUri, final String userId, final String userSecret,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Support Authentication to Token Endpoint using HTTP Basic with POST");

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

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

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

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

    // 2. Request authorization
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String state = UUID.randomUUID().toString();

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

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

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

    String authorizationCode = authorizationResponse.getCode();

    // 3. Get Access Token
    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, "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");
}
 
Example 10
Source File: SupportAuthenticationToTokenEndpointWithAsymmetricallySignedJWTs.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "redirectUri", "userId", "userSecret", "sectorIdentifierUri", "clientJwksUri",
        "RS256_keyId", "dnName", "keyStoreFile", "keyStoreSecret"})
@Test
public void supportAuthenticationToTokenEndpointWithAsymmetricallySignedJWTsRS256(
        final String redirectUris, final String redirectUri, final String userId, final String userSecret,
        final String sectorIdentifierUri, final String clientJwksUri,
        final String keyId, final String dnName, final String keyStoreFile, final String keyStoreSecret) throws Exception {
    showTitle("OC5:FeatureTest-Support Authentication to Token Endpoint with Asymmetrically Signed JWTs (RS256)");

    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setJwksUri(clientJwksUri);

    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<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String state = UUID.randomUUID().toString();

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

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

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

    String authorizationCode = authorizationResponse.getCode();

    // 3. Get Access Token
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.RS256);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setKeyId(keyId);
    tokenRequest.setAudience(tokenEndpoint);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);

    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.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
}
 
Example 11
Source File: PkceHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void tokenWithPkceCheck(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("tokenWithPkceCheck");

    // 1. Register client
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN);

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setResponseTypes(responseTypes);

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

    showClient(registerClient);
    assertOk(registerResponse);
    assertNotNull(registerResponse.getRegistrationAccessToken());

    // 3. 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, registerResponse.getClientId(), scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    CodeVerifier verifier = authorizationRequest.generateAndSetCodeChallengeWithMethod();

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

    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse.getIdToken(), "The ID Token is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");
    assertNotNull(authorizationResponse.getScope(), "The scope is null");

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

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

    // 5. Get Access Token
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(registerResponse.getClientId());
    tokenRequest.setAuthPassword(registerResponse.getClientSecret());
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);
    tokenRequest.setCodeVerifier(verifier.getCodeVerifier());

    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.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");

}
 
Example 12
Source File: ResponseTypesRestrictionHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
/**
 * Registering without provide the response_types param, should register the Client using only
 * the <code>code</code> response type.
 */
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void omittedResponseTypes(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("omittedResponseTypes");

    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);
    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();
    String registrationAccessToken = registerResponse.getRegistrationAccessToken();
    String registrationClientUri = registerResponse.getRegistrationClientUri();

    // 2. Client read
    RegisterRequest readClientRequest = new RegisterRequest(registrationAccessToken);

    RegisterClient readClient = new RegisterClient(registrationClientUri);
    readClient.setRequest(readClientRequest);
    RegisterResponse readClientResponse = readClient.exec();

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

    assertNotNull(readClientResponse.getClaims().get(RESPONSE_TYPES.toString()));
    assertNotNull(readClientResponse.getClaims().get(REDIRECT_URIS.toString()));
    assertNotNull(readClientResponse.getClaims().get(APPLICATION_TYPE.toString()));
    assertNotNull(readClientResponse.getClaims().get(CLIENT_NAME.toString()));
    assertNotNull(readClientResponse.getClaims().get(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
    assertNotNull(readClientResponse.getClaims().get(SCOPE.toString()));

    // 3. Request authorization
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);
    List<String> scopes = Arrays.asList(
            "openid",
            "profile",
            "address",
            "email");
    String state = UUID.randomUUID().toString();

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

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

    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");
    assertNotNull(authorizationResponse.getScope(), "The scope is null");

    String authorizationCode = authorizationResponse.getCode();

    // 4. Get Access Token
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    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.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
}
 
Example 13
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 14
Source File: SupportScopeRequestingNoSpecificClaims.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void supportScopeRequestingNoSpecificClaims(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Support scope Requesting No Specific Claims");

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

    // 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
    List<String> scopes = Arrays.asList("openid");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();

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

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

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

    String authorizationCode = authorizationResponse.getCode();

    // 3. Get Access Token
    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, "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");

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

    // 4. Request user info
    UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);

    showClient(userInfoClient);
    assertEquals(userInfoResponse.getStatus(), 200, "Unexpected response code: " + userInfoResponse.getStatus());
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));

    // 5. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));

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

    assertTrue(rsaSigner.validate(jwt));
}
 
Example 15
Source File: UmaTokenService.java    From oxd with Apache License 2.0 4 votes vote down vote up
private Token obtainTokenWithUserCredentials(OpenIdConfigurationResponse discovery, Rp rp, UmaScopeType scopeType) {

        // 1. Request authorization and receive the authorization code.
        final List<ResponseType> responseTypes = Lists.newArrayList();
        responseTypes.add(ResponseType.CODE);
        responseTypes.add(ResponseType.ID_TOKEN);

        final String state = stateService.generateState();

        final AuthorizationRequest request = new AuthorizationRequest(responseTypes, rp.getClientId(), scopes(scopeType), rp.getRedirectUri(), null);
        request.setState(state);
        request.setAuthUsername(rp.getUserId());
        request.setAuthPassword(rp.getUserSecret());
        request.getPrompts().add(Prompt.NONE);

        final AuthorizeClient authorizeClient = new AuthorizeClient(discovery.getAuthorizationEndpoint());
        authorizeClient.setExecutor(httpService.getClientExecutor());
        authorizeClient.setRequest(request);
        final AuthorizationResponse response1 = authorizeClient.exec();

        final String scope = response1.getScope();
        final String authorizationCode = response1.getCode();
        if (!state.equals(response1.getState())) {
            throw new HttpException(ErrorResponseCode.INVALID_STATE);
        }

        if (Util.allNotBlank(authorizationCode)) {

            // 2. Request access token using the authorization code.
            final TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
            tokenRequest.setCode(authorizationCode);
            tokenRequest.setRedirectUri(rp.getRedirectUri());
            tokenRequest.setAuthUsername(rp.getClientId());
            tokenRequest.setAuthPassword(rp.getClientSecret());
            tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
            tokenRequest.setScope(scope);

            final TokenClient tokenClient1 = new TokenClient(discovery.getTokenEndpoint());
            tokenClient1.setRequest(tokenRequest);
            tokenClient1.setExecutor(httpService.getClientExecutor());
            final TokenResponse response2 = tokenClient1.exec();

            if (response2.getStatus() == 200 && Util.allNotBlank(response2.getAccessToken())) {
                final Token token = TokenFactory.newToken(scopeType);
                token.setToken(response2.getAccessToken());
                token.setRefreshToken(response2.getRefreshToken());
                token.setExpiresIn(response2.getExpiresIn());
                return token;
            } else {
                LOG.error("Status: " + response2.getStatus() + ", Entity: " + response2.getEntity());
            }
        } else {
            LOG.debug("Authorization code is blank.");
        }
        throw new RuntimeException("Failed to obtain Token, scopeType: " + scopeType + ", site: " + rp);
    }
 
Example 16
Source File: AuthorizationCodeFlowHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void authorizationCodeWithNotAllowedScopeFlow(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("authorizationCodeWithNotAllowedScopeFlow");

    List<ResponseType> responseTypes = Arrays.asList(
            ResponseType.CODE,
            ResponseType.ID_TOKEN);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email", "user_name");

    // 1. Register client
    RegisterResponse registerResponse = registerClient(redirectUris, responseTypes, scopes, sectorIdentifierUri);

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

    // 2. Request authorization and receive the authorization code.
    List<String> authorizationScopes = Arrays.asList("openid", "profile", "address", "email", "user_name", "mobile_phone");
    String nonce = UUID.randomUUID().toString();
    AuthorizationResponse authorizationResponse = requestAuthorization(userId, userSecret, redirectUri, responseTypes, authorizationScopes, clientId, nonce);

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

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

    // 4. Request access token
    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, "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");

    String accessToken = tokenResponse.getAccessToken();

    // 5. Request user info
    UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);

    showClient(userInfoClient);
    assertEquals(userInfoResponse.getStatus(), 200, "Unexpected response code: " + userInfoResponse.getStatus());
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.NAME));
    assertNotNull(userInfoResponse.getClaim("user_name"));
    assertNull(userInfoResponse.getClaim("phone_mobile_number"));
}
 
Example 17
Source File: SupportAuthenticationToTokenEndpointWithAsymmetricallySignedJWTs.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "redirectUri", "userId", "userSecret", "sectorIdentifierUri", "clientJwksUri",
        "ES256_keyId", "dnName", "keyStoreFile", "keyStoreSecret"})
@Test
public void supportAuthenticationToTokenEndpointWithAsymmetricallySignedJWTsES256(
        final String redirectUris, final String redirectUri, final String userId, final String userSecret,
        final String sectorIdentifierUri, final String clientJwksUri,
        final String keyId, final String dnName, final String keyStoreFile, final String keyStoreSecret) throws Exception {
    showTitle("OC5:FeatureTest-Support Authentication to Token Endpoint with Asymmetrically Signed JWTs (ES256)");

    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setJwksUri(clientJwksUri);

    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<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String state = UUID.randomUUID().toString();

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

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

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

    String authorizationCode = authorizationResponse.getCode();

    // 3. Get Access Token
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.ES256);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setKeyId(keyId);
    tokenRequest.setAudience(tokenEndpoint);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);

    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.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
}
 
Example 18
Source File: TokenSignaturesHttpTest.java    From oxAuth with 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 File: AuthorizationCodeFlowOperation.java    From oxd with Apache License 2.0 4 votes vote down vote up
private AuthorizationCodeFlowResponse requestToken(OpenIdConfigurationResponse discovery, AuthorizationCodeFlowParams params) {
    // 1. Request authorization and receive the authorization code.
    final List<ResponseType> responseTypes = new ArrayList<ResponseType>();
    responseTypes.add(ResponseType.CODE);
    responseTypes.add(ResponseType.ID_TOKEN);
    final List<String> scopes = new ArrayList<String>();
    scopes.add(params.getScope());

    String nonce = params.getNonce();
    final AuthorizationRequest request = new AuthorizationRequest(responseTypes, params.getClientId(), scopes, params.getRedirectUrl(), nonce);
    request.setState("af0ifjsldkj");
    request.setAuthUsername(params.getUserId());
    request.setAuthPassword(params.getUserSecret());
    request.getPrompts().add(Prompt.NONE);
    request.setNonce(UUID.randomUUID().toString());
    request.setAcrValues(acrValues(params.getAcr()));

    final AuthorizeClient authorizeClient = new AuthorizeClient(discovery.getAuthorizationEndpoint());
    authorizeClient.setRequest(request);
    authorizeClient.setExecutor(getHttpService().getClientExecutor());
    final AuthorizationResponse response1 = authorizeClient.exec();

    final String scope = response1.getScope();
    final String authorizationCode = response1.getCode();

    if (Util.allNotBlank(authorizationCode)) {

        // 2. Request access token using the authorization code.
        final TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
        tokenRequest.setCode(authorizationCode);
        tokenRequest.setRedirectUri(params.getRedirectUrl());
        tokenRequest.setAuthUsername(params.getClientId());
        tokenRequest.setAuthPassword(params.getClientSecret());
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
        tokenRequest.setScope(scope);

        final TokenClient tokenClient1 = new TokenClient(discovery.getTokenEndpoint());
        tokenClient1.setExecutor(getHttpService().getClientExecutor());
        tokenClient1.setRequest(tokenRequest);
        final TokenResponse response2 = tokenClient1.exec();

        if (response2.getStatus() == 200 || response2.getStatus() == 302) { // success or redirect
            if (Util.allNotBlank(response2.getAccessToken(), response2.getRefreshToken())) {
                final AuthorizationCodeFlowResponse opResponse = new AuthorizationCodeFlowResponse();
                opResponse.setAccessToken(response2.getAccessToken());
                opResponse.setIdToken(response2.getIdToken());
                opResponse.setRefreshToken(response2.getRefreshToken());
                opResponse.setAuthorizationCode(authorizationCode);
                opResponse.setScope(scope);
                opResponse.setExpiresIn(response2.getExpiresIn());
                return opResponse;
            }
        }
    } else {
        LOG.debug("Authorization code is blank.");
    }
    return null;
}
 
Example 20
Source File: MTSLClientAuthenticationTest.java    From oxAuth with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        File jdkJks = new File("u:\\tmp\\ce-ob\\clientkeystore");
        if (!jdkJks.exists()) {
            throw new RuntimeException("Failed to find jks trust store");
        }

        File certificate = new File("u:\\tmp\\ce-ob\\fullchain.p12");
        if (!certificate.exists()) {
            throw new RuntimeException("Failed to find certificate");
        }

        HttpClient httpclient = new DefaultHttpClient();
// truststore
        KeyStore ts = KeyStore.getInstance("JKS", "SUN");
        ts.load(new FileInputStream(jdkJks), "secret".toCharArray());
// if you remove me, you've got 'javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated' on missing truststore
        if(0 == ts.size()) throw new IOException("Error loading truststore");
// tmf
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);
// keystore
        KeyStore ks = KeyStore.getInstance("PKCS12", "SunJSSE");
        ks.load(new FileInputStream(certificate), "".toCharArray());
// if you remove me, you've got 'javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated' on missing keystore
        if(0 == ks.size()) throw new IOException("Error loading keystore");
// kmf
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, "".toCharArray());
// SSL
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
// socket
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        String clientId = "@!D445.22BF.5EF1.0D87!0001!03F2.297D!0008!F599.E2C7";
        String clientSecret = "testClientSecret";

        TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
        tokenRequest.setCode("testCode");
        tokenRequest.setRedirectUri("https://ce-ob.gluu.org/cas/login");
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.TLS_CLIENT_AUTH);

        TokenClient tokenClient = new TokenClient("https://ce-ob.gluu.org/oxauth/restv1/token");
        tokenClient.setExecutor(new ApacheHttpClient4Executor(httpclient));
        tokenClient.setRequest(tokenRequest);
        TokenResponse tokenResponse = tokenClient.exec();

        System.out.println(tokenResponse);
        showClient(tokenClient);
    }