org.gluu.oxauth.model.common.AuthenticationMethod Java Examples

The following examples show how to use org.gluu.oxauth.model.common.AuthenticationMethod. 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: Supports3rdPartyInitLoginNoHttps.java    From oxAuth with MIT License 6 votes vote down vote up
@Parameters({"redirectUri", "clientJwksUri", "postLogoutRedirectUri"})
@Test
public void supports3rdPartyInitLoginNoHttps(final String redirectUri, final String clientJwksUri, final String postLogoutRedirectUri) throws Exception {
    showTitle("supports3rdPartyInitLoginNoHttps");

    // 1. Register Client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUri));
    registerRequest.setContacts(Arrays.asList("[email protected]"));
    registerRequest.setGrantTypes(Arrays.asList(AUTHORIZATION_CODE));
    registerRequest.setResponseTypes(Arrays.asList(CODE));
    registerRequest.setInitiateLoginUri("http://client.example.com/start-3rd-party-initiated-sso");
    registerRequest.setJwksUri(clientJwksUri);
    registerRequest.setPostLogoutRedirectUris(Arrays.asList(postLogoutRedirectUri));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);

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

    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 400, "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getEntity(), "The entity is null");
    assertNotNull(registerResponse.getErrorType(), "The error type is null");
    assertNotNull(registerResponse.getErrorDescription(), "The error description is null");
}
 
Example #2
Source File: ClientAuthenticationFilterEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Parameters({"tokenPath", "userId", "userSecret"})
@Test(dependsOnMethods = "requestClientRegistrationWithCustomAttributes")
public void requestAccessTokenCustomClientAuth2(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.setUsername(userId);
	tokenRequest.setPassword(userSecret);
	tokenRequest.setScope("profile email");
	tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);
	tokenRequest.addCustomParameter("myCustomAttr1", customAttrValue1);

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

	showResponse("requestAccessTokenCustomClientAuth2", 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"));
	assertTrue(!entity.equals(null), "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("refresh_token"), "Unexpected result: refresh_token not found");
		assertTrue(jsonObj.has("scope"), "Unexpected result: scope not found");
	} catch (JSONException e) {
		e.printStackTrace();
		fail(e.getMessage() + "\nResponse was: " + entity);
	}
}
 
Example #3
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Register a client with Token Endpoint Auth Method
 * <code>client_secret_basic</code>.
 */
@Parameters({"registerPath", "redirectUris"})
@Test
public void tokenEndpointAuthMethodClientSecretBasicStep1(final String registerPath, final String redirectUris)
        throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

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

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

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

    showResponse("tokenEndpointAuthMethodClientSecretBasicStep1", 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(RegisterResponseParam.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()));

        clientId2 = jsonObj.getString(RegisterResponseParam.CLIENT_ID.toString());
        clientSecret2 = jsonObj.getString(RegisterResponseParam.CLIENT_SECRET.toString());
        registrationAccessToken2 = jsonObj.getString(RegisterResponseParam.REGISTRATION_ACCESS_TOKEN.toString());
        registrationClientUri2 = jsonObj.getString(RegisterResponseParam.REGISTRATION_CLIENT_URI.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #4
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 #5
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * 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 #6
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Register a client with Token Endpoint Auth Method
 * <code>client_secret_post</code>.
 */
@Parameters({"registerPath", "redirectUris"})
@Test
public void tokenEndpointAuthMethodClientSecretPostStep1(final String registerPath, final String redirectUris)
        throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

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

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

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

    showResponse("tokenEndpointAuthMethodClientSecretPostStep1", 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(RegisterResponseParam.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()));

        clientId3 = jsonObj.getString(RegisterResponseParam.CLIENT_ID.toString());
        clientSecret3 = jsonObj.getString(RegisterResponseParam.CLIENT_SECRET.toString());
        registrationAccessToken3 = jsonObj.getString(RegisterResponseParam.REGISTRATION_ACCESS_TOKEN.toString());
        registrationClientUri3 = jsonObj.getString(RegisterResponseParam.REGISTRATION_CLIENT_URI.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #7
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Fail 2: Call to Token Endpoint with Auth Method
 * <code>client_secret_post</code> should fail.
 */
@Parameters({"tokenPath", "userId", "userSecret"})
@Test(dependsOnMethods = "tokenEndpointAuthMethodPrivateKeyJwtStep2")
public void tokenEndpointAuthMethodPrivateKeyJwtFail2(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_POST);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId5);
    tokenRequest.setAuthPassword(clientSecret5);

    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("tokenEndpointAuthMethodPrivateKeyJwtFail2", 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 #8
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Fail 1: Call to Token Endpoint with Auth Method
 * <code>client_secret_basic</code> should fail.
 */
@Parameters({"tokenPath", "userId", "userSecret"})
@Test(dependsOnMethods = "tokenEndpointAuthMethodClientSecretJwtStep2")
public void tokenEndpointAuthMethodClientSecretJwtFail1(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(clientId4);
    tokenRequest.setAuthPassword(clientSecret4);

    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("tokenEndpointAuthMethodClientSecretJwtFail1", 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 #9
Source File: ClientAuthenticationByAccessTokenHttpTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void requestClientRegistrationWithCustomAttributes() throws Exception {
    showTitle("requestClientRegistrationWithCustomAttributes");

    List<ResponseType> responseTypes = Arrays.asList(
            ResponseType.CODE,
            ResponseType.TOKEN,
            ResponseType.ID_TOKEN);
    List<GrantType> grantTypes = Arrays.asList(
            GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
    );

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", Collections.singletonList(REDIRECT_URI));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setGrantTypes(grantTypes);
    registerRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setExecutor(clientExecutor(true));
    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());

    clientId = response.getClientId();
    clientSecret = response.getClientSecret();
}
 
Example #10
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Fail 3: Call to Token Endpoint with Auth Method
 * <code>client_secret_jwt</code> should fail.
 */
@Parameters({"tokenPath", "audience", "userId", "userSecret"})
@Test(dependsOnMethods = "tokenEndpointAuthMethodPrivateKeyJwtStep2")
public void tokenEndpointAuthMethodPrivateKeyJwtFail3(final String tokenPath, final String audience,
                                                      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_JWT);
    tokenRequest.setAudience(audience);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId5);
    tokenRequest.setAuthPassword(clientSecret5);

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

    showResponse("tokenEndpointAuthMethodPrivateKeyJwtFail3", 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 #11
Source File: TokenRequest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Constructs a token request.
 *
 * @param grantType The grant type is mandatory and could be:
 *                  <code>authorization_code</code>, <code>password</code>,
 *                  <code>client_credentials</code>, <code>refresh_token</code>.
 */
public TokenRequest(GrantType grantType) {
    super();
    this.grantType = grantType;

    setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
}
 
Example #12
Source File: ClientAuthnRequest.java    From oxAuth with MIT License 5 votes vote down vote up
public void appendClientAuthnToQuery(QueryBuilder builder) {
    if (getAuthenticationMethod() == AuthenticationMethod.CLIENT_SECRET_POST) {
        builder.append("client_id", getAuthUsername());
        builder.append("client_secret", getAuthPassword());
    } else if (getAuthenticationMethod() == AuthenticationMethod.CLIENT_SECRET_JWT ||
            getAuthenticationMethod() == AuthenticationMethod.PRIVATE_KEY_JWT) {
        builder.append("client_assertion_type", ClientAssertionType.JWT_BEARER.toString());
        builder.append("client_assertion", getClientAssertion());
    }
}
 
Example #13
Source File: ClientAuthnEnabler.java    From oxAuth with MIT License 5 votes vote down vote up
public void exec(ClientAuthnRequest request){
    if (request.getAuthenticationMethod() == AuthenticationMethod.CLIENT_SECRET_BASIC
            && request.hasCredentials()) {
        clientRequest.header("Authorization", "Basic " + request.getEncodedCredentials());
        return;
    }

    if (request.getAuthenticationMethod() == AuthenticationMethod.CLIENT_SECRET_POST) {
        if (request.getAuthUsername() != null && !request.getAuthUsername().isEmpty()) {
            clientRequest.formParameter("client_id", request.getAuthUsername());
        }
        if (request.getAuthPassword() != null && !request.getAuthPassword().isEmpty()) {
            clientRequest.formParameter("client_secret", request.getAuthPassword());
        }
        return;
    }
    if (request.getAuthenticationMethod() == AuthenticationMethod.CLIENT_SECRET_JWT ||
            request.getAuthenticationMethod() == AuthenticationMethod.PRIVATE_KEY_JWT) {
        clientRequest.formParameter("client_assertion_type", ClientAssertionType.JWT_BEARER);
        if (request.getClientAssertion() != null) {
            clientRequest.formParameter("client_assertion", request.getClientAssertion());
        }
        if (request.getAuthUsername() != null && !request.getAuthUsername().isEmpty()) {
            clientRequest.formParameter("client_id", request.getAuthUsername());
        }
    }
}
 
Example #14
Source File: UsesDynamicRegistration.java    From oxAuth with MIT License 5 votes vote down vote up
@Parameters({"redirectUris", "sectorIdentifierUri", "clientJwksUri"})
@Test
public void usesDynamicRegistration(final String redirectUris, final String sectorIdentifierUri,
                                       final String clientJwksUri) throws Exception {
    showTitle("OC5:FeatureTest-Uses Dynamic Registration");

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setContacts(Arrays.asList("[email protected]", "[email protected]"));
    registerRequest.setLogoUri("http://www.gluu.org/wp-content/themes/gluursn/images/logo.png");
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
    registerRequest.setPolicyUri("http://www.gluu.org/policy");
    registerRequest.setJwksUri(clientJwksUri);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setSubjectType(SubjectType.PUBLIC);
    registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS256);

    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.getRegistrationClientUri());
    assertNotNull(response.getClientIdIssuedAt());
    assertNotNull(response.getClientSecretExpiresAt());
}
 
Example #15
Source File: TokenAction.java    From oxAuth with MIT License 5 votes vote down vote up
public void exec() {
    try {
        TokenRequest request = new TokenRequest(grantType);
        request.setAuthUsername(clientId);
        request.setAuthPassword(clientSecret);
        request.setCode(code);
        request.setRedirectUri(redirectUri);
        request.setUsername(username);
        request.setPassword(password);
        request.setScope(scope);
        request.setAssertion(assertion);
        request.setRefreshToken(refreshToken);
        request.setAuthenticationMethod(authenticationMethod);
        if (authenticationMethod.equals(AuthenticationMethod.CLIENT_SECRET_JWT)) {
            request.setAudience(tokenEndpoint);
        }
        request.setAuthReqId(authReqId);

        TokenClient client = new TokenClient(tokenEndpoint);
        client.setRequest(request);
        TokenResponse response = client.exec();

        if (response.getStatus() == 200) {
            userInfoAction.setAccessToken(response.getAccessToken());
        }

        showResults = true;
        requestString = client.getRequestAsString();
        responseString = client.getResponseAsString();
    } catch (Exception e) {
    	log.error(e.getMessage(), e);
    }
}
 
Example #16
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Fail 1: Call to Token Endpoint with Auth Method
 * <code>client_secret_post</code> should fail.
 */
@Parameters({"tokenPath", "userId", "userSecret"})
@Test(dependsOnMethods = "tokenEndpointAuthMethodClientSecretBasicStep2")
public void tokenEndpointAuthMethodClientSecretBasicFail1(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_POST);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId2);
    tokenRequest.setAuthPassword(clientSecret2);

    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("tokenEndpointAuthMethodClientSecretBasicFail1", 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 #17
Source File: ClientService.java    From oxAuth with MIT License 4 votes vote down vote up
public boolean isPublic(Client client) {
 return client != null && client.getAuthenticationMethod() == AuthenticationMethod.NONE;
}
 
Example #18
Source File: SupportAuthenticationToTokenEndpointWithAsymmetricallySignedJWTs.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "redirectUri", "userId", "userSecret", "sectorIdentifierUri", "clientJwksUri",
        "ES384_keyId", "dnName", "keyStoreFile", "keyStoreSecret"})
@Test
public void supportAuthenticationToTokenEndpointWithAsymmetricallySignedJWTsES384(
        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 (ES384)");

    // 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.ES384);
    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 #19
Source File: CanMakeAccessTokenRequestWithClientSecretPostAuthentication.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "redirectUri", "userId", "userSecret", "sectorIdentifierUri"})
@Test
public void canMakeAccessTokenRequestWithClientSecretPostAuthentication(
        final String redirectUris, final String redirectUri, final String userId, final String userSecret,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Can Make Access Token Request with client secret post Authentication");

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

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

    // 2. Request authorization
    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_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 #20
Source File: ClientCredentialsGrantHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "clientJwksUri", "ES512_keyId", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void privateKeyJwtAuthenticationMethodES512(
        final String redirectUris, final String clientJwksUri, final String keyId, final String dnName,
        final String keyStoreFile, final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
    showTitle("privateKeyJwtAuthenticationMethodES512");

    List<String> scopes = Arrays.asList("clientinfo");
    List<GrantType> grantTypes = Arrays.asList(
            GrantType.CLIENT_CREDENTIALS
    );

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

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

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

    String clientId = registerResponse.getClientId();

    // 2. Request Client Credentials Grant
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    TokenRequest tokenRequest = new TokenRequest(GrantType.CLIENT_CREDENTIALS);
    tokenRequest.setScope("clientinfo");
    tokenRequest.setAuthUsername(clientId);
    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());
    assertNotNull(tokenResponse.getAccessToken());
    assertNotNull(tokenResponse.getTokenType());
    assertNotNull(tokenResponse.getScope());
    assertNull(tokenResponse.getRefreshToken());

    String accessToken = tokenResponse.getAccessToken();

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

    showClient(clientInfoClient);
    assertEquals(clientInfoResponse.getStatus(), 200, "Unexpected response code: " + clientInfoResponse.getStatus());
    assertNotNull(clientInfoResponse.getClaim("displayName"), "Unexpected result: displayName not found");
    assertNotNull(clientInfoResponse.getClaim("inum"), "Unexpected result: inum not found");
}
 
Example #21
Source File: ClientAuthenticationFilterHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUri"})
@Test(dependsOnMethods = "requestClientRegistrationWithCustomAttributes")
public void requestAccessTokenCustomClientAuth1(final String userId, final String userSecret,
                                                final String redirectUri) 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, redirectUri, nonce);
    authorizationRequest.setState(state);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);
    authorizationRequest.getPrompts().add(Prompt.NONE);

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

    showClient(authorizeClient);
    assertEquals(authorizationResponse.getStatus(), 302, "Unexpected response code: " + authorizationResponse.getStatus());
    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.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));

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

    assertTrue(rsaSigner.validate(jwt));
    assertTrue(rsaSigner.validateAuthorizationCode(authorizationCode, jwt));

    // 3. Request access token using the authorization code.
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    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.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
}
 
Example #22
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 #23
Source File: ClientCredentialsGrantHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "clientJwksUri", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void privateKeyJwtAuthenticationMethodPS512Fail(
        final String redirectUris, final String clientJwksUri, final String dnName, final String keyStoreFile,
        final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
    showTitle("privateKeyJwtAuthenticationMethodPS512Fail");

    List<String> scopes = Arrays.asList("clientinfo");

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

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

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

    String clientId = registerResponse.getClientId();

    // 2. Request Client Credentials Grant
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    TokenRequest tokenRequest = new TokenRequest(GrantType.CLIENT_CREDENTIALS);
    tokenRequest.setScope("clientinfo");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.PS512);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setKeyId("PS512SIG_INVALID_KEYID");
    tokenRequest.setAudience(tokenEndpoint);

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

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 401, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getErrorType());
    assertEquals(tokenResponse.getErrorType(), TokenErrorResponseType.INVALID_CLIENT);
    assertNotNull(tokenResponse.getErrorDescription());
}
 
Example #24
Source File: ImplicitFlowOperation.java    From oxd with Apache License 2.0 4 votes vote down vote up
private ImplicitFlowResponse requestToken(OpenIdConfigurationResponse discovery, ImplicitFlowParams 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());

    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 ImplicitFlowResponse opResponse = new ImplicitFlowResponse();
                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 #25
Source File: ClientCredentialsGrantHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "clientJwksUri", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void privateKeyJwtAuthenticationMethodPS384Fail(
        final String redirectUris, final String clientJwksUri, final String dnName, final String keyStoreFile,
        final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
    showTitle("privateKeyJwtAuthenticationMethodPS384Fail");

    List<String> scopes = Arrays.asList("clientinfo");

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

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

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

    String clientId = registerResponse.getClientId();

    // 2. Request Client Credentials Grant
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    TokenRequest tokenRequest = new TokenRequest(GrantType.CLIENT_CREDENTIALS);
    tokenRequest.setScope("clientinfo");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.PS384);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setKeyId("PS384SIG_INVALID_KEYID");
    tokenRequest.setAudience(tokenEndpoint);

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

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 401, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getErrorType());
    assertEquals(tokenResponse.getErrorType(), TokenErrorResponseType.INVALID_CLIENT);
    assertNotNull(tokenResponse.getErrorDescription());
}
 
Example #26
Source File: ClientCredentialsGrantHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "clientJwksUri", "PS384_keyId", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void privateKeyJwtAuthenticationMethodPS384(
        final String redirectUris, final String clientJwksUri, final String keyId, final String dnName,
        final String keyStoreFile, final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
    showTitle("privateKeyJwtAuthenticationMethodPS384");

    List<String> scopes = Arrays.asList("clientinfo");
    List<GrantType> grantTypes = Arrays.asList(
            GrantType.CLIENT_CREDENTIALS
    );

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

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

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

    String clientId = registerResponse.getClientId();

    // 2. Request Client Credentials Grant
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    TokenRequest tokenRequest = new TokenRequest(GrantType.CLIENT_CREDENTIALS);
    tokenRequest.setScope("clientinfo");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.PS384);
    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());
    assertNotNull(tokenResponse.getAccessToken());
    assertNotNull(tokenResponse.getTokenType());
    assertNotNull(tokenResponse.getScope());
    assertNull(tokenResponse.getRefreshToken());

    String accessToken = tokenResponse.getAccessToken();

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

    showClient(clientInfoClient);
    assertEquals(clientInfoResponse.getStatus(), 200, "Unexpected response code: " + clientInfoResponse.getStatus());
    assertNotNull(clientInfoResponse.getClaim("displayName"), "Unexpected result: displayName not found");
    assertNotNull(clientInfoResponse.getClaim("inum"), "Unexpected result: inum not found");
}
 
Example #27
Source File: ClientCredentialsGrantHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "clientJwksUri", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void privateKeyJwtAuthenticationMethodPS256Fail(
        final String redirectUris, final String clientJwksUri, final String dnName, final String keyStoreFile,
        final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
    showTitle("privateKeyJwtAuthenticationMethodPS256Fail");

    List<String> scopes = Arrays.asList("clientinfo");

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

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

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

    String clientId = registerResponse.getClientId();

    // 2. Request Client Credentials Grant
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    TokenRequest tokenRequest = new TokenRequest(GrantType.CLIENT_CREDENTIALS);
    tokenRequest.setScope("clientinfo");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.PS256);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setKeyId("PS256SIG_INVALID_KEYID");
    tokenRequest.setAudience(tokenEndpoint);

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

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 401, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getErrorType());
    assertEquals(tokenResponse.getErrorType(), TokenErrorResponseType.INVALID_CLIENT);
    assertNotNull(tokenResponse.getErrorDescription());
}
 
Example #28
Source File: SupportScopeRequestingEmailClaims.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void supportScopeRequestingEmailClaims(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Support scope Requesting email 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", "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());

    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 #29
Source File: UserAuthenticationFilterEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"registerPath", "redirectUris", "clientJwksUri"})
@Test
public void requestAccessTokenCustomAuth4Step1(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.CLIENT_SECRET_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("requestAccessTokenCustomAuth4Step1", 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()));

        clientId4 = jsonObj.getString(RegisterResponseParam.CLIENT_ID.toString());
        clientSecret4 = jsonObj.getString(CLIENT_SECRET.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #30
Source File: ClientCredentialsGrantHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "clientJwksUri", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void privateKeyJwtAuthenticationMethodRS512Fail(
        final String redirectUris, final String clientJwksUri, final String dnName, final String keyStoreFile,
        final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
    showTitle("privateKeyJwtAuthenticationMethodRS512Fail");

    List<String> scopes = Arrays.asList("clientinfo");

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

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

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

    String clientId = registerResponse.getClientId();

    // 2. Request Client Credentials Grant
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    TokenRequest tokenRequest = new TokenRequest(GrantType.CLIENT_CREDENTIALS);
    tokenRequest.setScope("clientinfo");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
    tokenRequest.setAlgorithm(SignatureAlgorithm.RS512);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setKeyId("RS512SIG_INVALID_KEYID");
    tokenRequest.setAudience(tokenEndpoint);

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

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 401, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getErrorType());
    assertEquals(tokenResponse.getErrorType(), TokenErrorResponseType.INVALID_CLIENT);
    assertNotNull(tokenResponse.getErrorDescription());
}