Java Code Examples for org.gluu.oxauth.client.AuthorizationRequest#setAuthUsername()

The following examples show how to use org.gluu.oxauth.client.AuthorizationRequest#setAuthUsername() . 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: RejectRequestWithoutResponseType.java    From oxAuth with MIT License 6 votes vote down vote up
@Parameters({"userId", "userSecret"})
@Test
public void rejectRequestWithoutResponseType(final String userId, final String userSecret) throws Exception {
    showTitle("OC5:FeatureTest-Reject Request Without response type");

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(null, null, null, null, null);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);

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

    showClient(authorizeClient);
    assertEquals(authorizationResponse.getStatus(), 400, "Unexpected response code: " + authorizationResponse.getStatus());
    assertNotNull(authorizationResponse.getErrorType(), "The error type is null");
    assertNotNull(authorizationResponse.getErrorDescription(), "The error description is null");
}
 
Example 2
Source File: GetAuthorizationCodeOperation.java    From oxd with Apache License 2.0 5 votes vote down vote up
@Override
public IOpResponse execute(GetAuthorizationCodeParams params) {
    final Rp rp = getRp();

    String nonce = Strings.isNullOrEmpty(params.getNonce()) ? UUID.randomUUID().toString() : params.getNonce();
    String state = Strings.isNullOrEmpty(params.getState()) ? UUID.randomUUID().toString() : params.getState();

    final AuthorizationRequest request = new AuthorizationRequest(responseTypes(rp.getResponseTypes()),
            rp.getClientId(), rp.getScope(), rp.getRedirectUri(), nonce);
    request.setState(state);
    request.setAuthUsername(params.getUsername());
    request.setAuthPassword(params.getPassword());
    request.getPrompts().add(Prompt.NONE);
    request.setAcrValues(acrValues(params, rp));

    getStateService().putNonce(nonce);
    getStateService().putState(state);

    final AuthorizeClient authorizeClient = getOpClientFactory().createAuthorizeClient(getDiscoveryService().getConnectDiscoveryResponse(rp).getAuthorizationEndpoint());
    authorizeClient.setRequest(request);
    authorizeClient.setExecutor(getHttpService().getClientExecutor());
    final AuthorizationResponse response = authorizeClient.exec();

    if (response != null) {
        getStateService().putState(params.getState());
        return new GetAuthorizationCodeResponse(response.getCode());
    } else {
        LOG.error("Failed to get response from oxauth client.");
    }

    return null;
}
 
Example 3
Source File: ResponseTypesRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Authorization request with the other Response types combination should
 * fail.
 */
@Test(dependsOnMethods = "responseTypesTokenIdTokenStep3", dataProvider = "responseTypesTokenIdTokenStep4DataProvider")
public void responseTypesTokenIdTokenStep4(final String authorizePath, final String userId, final String userSecret,
                                           final String redirectUri, final List<ResponseType> responseTypes) throws Exception {
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId3, scopes,
            redirectUri, nonce);
    authorizationRequest.setState("af0ifjsldkj");
    authorizationRequest.getPrompts().add(Prompt.NONE);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);

    Builder request = ResteasyClientBuilder.newClient()
            .target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
    request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
    request.header("Accept", MediaType.TEXT_PLAIN);

    Response response = request.get();
    String entity = response.readEntity(String.class);

    showResponse("responseTypesTokenIdTokenStep4", response, entity);

    if (response.getStatus() == 400) {
        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);
        }
    } else {
        fail("Unexpected response code: " + response.getStatus());
    }
}
 
Example 4
Source File: ResponseTypesRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Authorization request with the other Response types combination should
 * fail.
 */
@Test(dependsOnMethods = "omittedResponseTypesStep3b", dataProvider = "responseTypesCodeIdTokenStep4DataProvider")
public void responseTypesCodeIdTokenStep4(final String authorizePath, final String userId, final String userSecret,
                                          final String redirectUri, final List<ResponseType> responseTypes) throws Exception {
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId1, scopes,
            redirectUri, nonce);
    authorizationRequest.setState("af0ifjsldkj");
    authorizationRequest.getPrompts().add(Prompt.NONE);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);

    Builder request = ResteasyClientBuilder.newClient()
            .target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
    request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
    request.header("Accept", MediaType.TEXT_PLAIN);

    Response response = request.get();
    String entity = response.readEntity(String.class);

    showResponse("responseTypesCodeIdTokenStep4", response, entity);

    if (response.getStatus() == 400) {
        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);
        }
    } else {
        fail("Unexpected response code: " + response.getStatus());
    }
}
 
Example 5
Source File: ResponseTypesRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Authorization request with the other Response types combination should
 * fail.
 */
@Test(dependsOnMethods = "omittedResponseTypesStep3b", dataProvider = "omittedResponseTypesStep4DataProvider")
public void omittedResponseTypesStep4(final String authorizePath, final String userId, final String userSecret,
                                      final String redirectUri, final List<ResponseType> responseTypes) throws Exception {
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId1, scopes,
            redirectUri, nonce);
    authorizationRequest.setState("af0ifjsldkj");
    authorizationRequest.getPrompts().add(Prompt.NONE);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);

    Builder request = ResteasyClientBuilder.newClient()
            .target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
    request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
    request.header("Accept", MediaType.TEXT_PLAIN);

    Response response = request.get();
    String entity = response.readEntity(String.class);

    showResponse("omittedResponseTypesStep4", response, entity);

    if (response.getStatus() == 400) {
        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);
        }
    } else {
        fail("Unexpected response code: " + response.getStatus());
    }
}
 
Example 6
Source File: AuthorizeWithResponseModeEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" })
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestAuthorizationTokenWithResponseModeQuery(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri) throws Exception {

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

	List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
	List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
	String nonce = UUID.randomUUID().toString();

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

	Builder request = ResteasyClientBuilder.newClient()
			.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
	request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
	request.header("Accept", MediaType.TEXT_PLAIN);

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestAuthorizationTokenWithResponseModeQuery", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	if (response.getLocation() != null) {
		try {
			URI uri = new URI(response.getLocation().toString());
			assertNotNull(uri.getQuery(), "Query is null");

			Map<String, String> params = QueryStringDecoder.decode(uri.getQuery());

			assertNotNull(params.get(AuthorizeResponseParam.ACCESS_TOKEN), "The access token is null");
			assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null");
			assertNotNull(params.get(AuthorizeResponseParam.TOKEN_TYPE), "The token type is null");
			assertNotNull(params.get(AuthorizeResponseParam.EXPIRES_IN), "The expires in value is null");
			assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope must be null");
			assertNull(params.get("refresh_token"), "The refresh_token must be null");
			assertEquals(params.get(AuthorizeResponseParam.STATE), state);
		} catch (URISyntaxException e) {
			e.printStackTrace();
			fail("Response URI is not well formed");
		}
	}
}
 
Example 7
Source File: AuthorizeWithResponseModeEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" })
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestAuthorizationTokenWithResponseModeFragment(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri) throws Exception {

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

	List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
	List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
	String nonce = UUID.randomUUID().toString();

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

	Builder request = ResteasyClientBuilder.newClient()
			.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
	request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
	request.header("Accept", MediaType.TEXT_PLAIN);

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestAuthorizationTokenWithResponseModeFragment", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	if (response.getLocation() != null) {
		try {
			URI uri = new URI(response.getLocation().toString());
			assertNotNull(uri.getFragment(), "Fragment is null");

			Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

			assertNotNull(params.get(AuthorizeResponseParam.ACCESS_TOKEN), "The access token is null");
			assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null");
			assertNotNull(params.get(AuthorizeResponseParam.TOKEN_TYPE), "The token type is null");
			assertNotNull(params.get(AuthorizeResponseParam.EXPIRES_IN), "The expires in value is null");
			assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope must be null");
			assertNull(params.get("refresh_token"), "The refresh_token must be null");
			assertEquals(params.get(AuthorizeResponseParam.STATE), state);
		} catch (URISyntaxException e) {
			e.printStackTrace();
			fail("Response URI is not well formed");
		}
	}
}
 
Example 8
Source File: AuthorizeWithResponseModeEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" })
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestAuthorizationCodeWithResponseModeFragment(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri) throws Exception {

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

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

	AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes,
			redirectUri, null);
	authorizationRequest.setState(state);
	authorizationRequest.getPrompts().add(Prompt.NONE);
	authorizationRequest.setAuthUsername(userId);
	authorizationRequest.setAuthPassword(userSecret);
	authorizationRequest.setResponseMode(ResponseMode.FRAGMENT);

	Builder request = ResteasyClientBuilder.newClient()
			.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
	request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
	request.header("Accept", MediaType.TEXT_PLAIN);

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestAuthorizationCodeWithResponseModeFragment", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	try {
		URI uri = new URI(response.getLocation().toString());
		assertNotNull(uri.getFragment(), "Fragment is null");

		Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

		assertNotNull(params.get(AuthorizeResponseParam.CODE), "The code is null");
		assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope is null");
		assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null");

		assertEquals(params.get(AuthorizeResponseParam.STATE), state);
	} catch (URISyntaxException e) {
		e.printStackTrace();
		fail("Response URI is not well formed");
	}
}
 
Example 9
Source File: AuthorizeWithResponseModeEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" })
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestAuthorizationCodeWithResponseModeQuery(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri) throws Exception {
	final String state = UUID.randomUUID().toString();

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

	AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes,
			redirectUri, null);
	authorizationRequest.setState(state);
	authorizationRequest.getPrompts().add(Prompt.NONE);
	authorizationRequest.setAuthUsername(userId);
	authorizationRequest.setAuthPassword(userSecret);
	authorizationRequest.setResponseMode(ResponseMode.QUERY);

	Builder request = ResteasyClientBuilder.newClient()
			.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
	request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
	request.header("Accept", MediaType.TEXT_PLAIN);

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestAuthorizationCodeWithResponseModeQuery", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	try {
		URI uri = new URI(response.getLocation().toString());
		assertNotNull(uri.getQuery(), "Query string is null");

		Map<String, String> params = QueryStringDecoder.decode(uri.getQuery());

		assertNotNull(params.get(AuthorizeResponseParam.CODE), "The code is null");
		assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope is null");
		assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null");
		assertEquals(params.get(AuthorizeResponseParam.STATE), state);
	} catch (URISyntaxException e) {
		e.printStackTrace();
		fail("Response URI is not well formed");
	}
}
 
Example 10
Source File: ResponseTypesRestrictionEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"authorizePath", "userId", "userSecret", "redirectUri"})
@Test(dependsOnMethods = "responseTypesTokenIdTokenStep2")
public void responseTypesTokenIdTokenStep3(final String authorizePath, final String userId, final String userSecret,
                                           final String redirectUri) throws Exception {
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId3, scopes,
            redirectUri, nonce);
    authorizationRequest.setState("af0ifjsldkj");
    authorizationRequest.getPrompts().add(Prompt.NONE);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);

    Builder request = ResteasyClientBuilder.newClient()
            .target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
    request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
    request.header("Accept", MediaType.TEXT_PLAIN);

    Response response = request.get();
    String entity = response.readEntity(String.class);

    showResponse("responseTypesTokenIdTokenStep3", response, entity);

    assertEquals(response.getStatus(), 302, "Unexpected response code.");
    assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

    if (response.getLocation() != null) {
        try {
            URI uri = new URI(response.getLocation().toString());
            assertNotNull(uri.getFragment(), "Fragment is null");

            Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

            assertNotNull(params.get("access_token"), "The access token is null");
            assertNotNull(params.get("token_type"), "The token type is null");
            assertNotNull(params.get("id_token"), "The id token is null");
            assertNotNull(params.get("state"), "The state is null");
        } catch (URISyntaxException e) {
            e.printStackTrace();
            fail("Response URI is not well formed");
        }
    }
}
 
Example 11
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 12
Source File: OpenIDRequestObjectWithESAlgEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri", "ES256_keyId", "dnName", "keyStoreFile",
		"keyStoreSecret" })
@Test(dependsOnMethods = "requestParameterMethodES256Step1")
public void requestParameterMethodES256Step2(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri, final String keyId, final String dnName,
		final String keyStoreFile, final String keyStoreSecret) throws Exception {
	Builder request = null;
	try {
		OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);
		List<String> scopes = Arrays.asList("openid");
		String nonce = UUID.randomUUID().toString();
		String state = UUID.randomUUID().toString();

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

		JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest,
				SignatureAlgorithm.ES256, cryptoProvider);
		jwtAuthorizationRequest.setKeyId(keyId);
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest
				.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
		jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE,
				ClaimValue.createValueList(new String[] {ACR_VALUE})));
		String authJwt = jwtAuthorizationRequest.getEncodedJwt();
		authorizationRequest.setRequest(authJwt);
		System.out.println("Request JWT: " + authJwt);

		request = ResteasyClientBuilder.newClient()
				.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
		request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
		request.header("Accept", MediaType.TEXT_PLAIN);
	} catch (Exception ex) {
		fail(ex.getMessage(), ex);
	}

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodES256Step2", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	try {
		URI uri = new URI(response.getLocation().toString());
		assertNotNull(uri.getFragment(), "Query string is null");

		Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

		assertNotNull(params.get("access_token"), "The accessToken is null");
		assertNotNull(params.get("scope"), "The scope is null");
		assertNotNull(params.get("state"), "The state is null");
	} catch (URISyntaxException e) {
		e.printStackTrace();
		fail(e.getMessage(), e);
	}
}
 
Example 13
Source File: OpenIDRequestObjectWithESAlgEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri", "ES384_keyId", "dnName", "keyStoreFile",
		"keyStoreSecret" })
@Test(dependsOnMethods = "requestParameterMethodES384Step1")
public void requestParameterMethodES384Step2(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri, final String keyId, final String dnName,
		final String keyStoreFile, final String keyStoreSecret) throws Exception {

	Builder request = null;
	try {
		OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);
		List<String> scopes = Arrays.asList("openid");
		String nonce = UUID.randomUUID().toString();
		String state = UUID.randomUUID().toString();

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

		JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest,
				SignatureAlgorithm.ES384, cryptoProvider);
		jwtAuthorizationRequest.setKeyId(keyId);
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest
				.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
		jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE,
				ClaimValue.createValueList(new String[] { ACR_VALUE })));
		String authJwt = jwtAuthorizationRequest.getEncodedJwt();
		authorizationRequest.setRequest(authJwt);
		System.out.println("Request JWT: " + authJwt);

		request = ResteasyClientBuilder.newClient()
				.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
		request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
		request.header("Accept", MediaType.TEXT_PLAIN);
	} catch (Exception ex) {
		fail(ex.getMessage(), ex);
	}

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodES384Step2", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	try {
		URI uri = new URI(response.getLocation().toString());
		assertNotNull(uri.getFragment(), "Query string is null");

		Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

		assertNotNull(params.get("access_token"), "The accessToken is null");
		assertNotNull(params.get("scope"), "The scope is null");
		assertNotNull(params.get("state"), "The state is null");
	} catch (URISyntaxException e) {
		fail(e.getMessage(), e);
	}
}
 
Example 14
Source File: OpenIDRequestObjectWithESAlgEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri", "ES512_keyId", "dnName", "keyStoreFile",
		"keyStoreSecret" })
@Test(dependsOnMethods = "requestParameterMethodES512Step1")
public void requestParameterMethodES512Step2(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri, final String keyId, final String dnName,
		final String keyStoreFile, final String keyStoreSecret) throws Exception {
	Builder request = null;
	try {

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

		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);
		List<String> scopes = Arrays.asList("openid");
		String nonce = UUID.randomUUID().toString();
		String state = UUID.randomUUID().toString();

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

		JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest,
				SignatureAlgorithm.ES512, cryptoProvider);
		jwtAuthorizationRequest.setKeyId(keyId);
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest
				.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
		jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE,
				ClaimValue.createValueList(new String[] { ACR_VALUE })));
		String authJwt = jwtAuthorizationRequest.getEncodedJwt();
		authorizationRequest.setRequest(authJwt);
		System.out.println("Request JWT: " + authJwt);

		request = ResteasyClientBuilder.newClient()
				.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
		request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
		request.header("Accept", MediaType.TEXT_PLAIN);
	} catch (Exception ex) {
		fail(ex.getMessage(), ex);
	}

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodES512Step2", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	try {
		URI uri = new URI(response.getLocation().toString());
		assertNotNull(uri.getFragment(), "Query string is null");

		Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

		assertNotNull(params.get("access_token"), "The accessToken is null");
		assertNotNull(params.get("scope"), "The scope is null");
		assertNotNull(params.get("state"), "The state is null");
	} catch (URISyntaxException e) {
		fail(e.getMessage(), e);
	}
}
 
Example 15
Source File: OpenIDRequestObjectWithESAlgEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri", "ES256_keyId", "dnName", "keyStoreFile",
		"keyStoreSecret" })
@Test(dependsOnMethods = "requestParameterMethodES256X509CertStep1")
public void requestParameterMethodES256X509CertStep2(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri, final String keyId, final String dnName,
		final String keyStoreFile, final String keyStoreSecret) throws Exception {
	Builder request = null;
	try {
		OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);
		List<String> scopes = Arrays.asList("openid");
		String nonce = UUID.randomUUID().toString();
		String state = UUID.randomUUID().toString();

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

		JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest,
				SignatureAlgorithm.ES256, cryptoProvider);
		jwtAuthorizationRequest.setKeyId(keyId);
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest
				.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
		jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE,
				ClaimValue.createValueList(new String[] { ACR_VALUE })));
		String authJwt = jwtAuthorizationRequest.getEncodedJwt();
		authorizationRequest.setRequest(authJwt);
		System.out.println("Request JWT: " + authJwt);

		request = ResteasyClientBuilder.newClient()
				.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
		request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
		request.header("Accept", MediaType.TEXT_PLAIN);
	} catch (Exception ex) {
		fail(ex.getMessage(), ex);
	}

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodES256X509CertStep2", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	try {
		URI uri = new URI(response.getLocation().toString());
		assertNotNull(uri.getFragment(), "Query string is null");

		Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

		assertNotNull(params.get("access_token"), "The accessToken is null");
		assertNotNull(params.get("scope"), "The scope is null");
		assertNotNull(params.get("state"), "The state is null");
	} catch (URISyntaxException e) {
		fail(e.getMessage(), e);
	}
}
 
Example 16
Source File: OpenIDRequestObjectWithESAlgEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri", "ES384_keyId", "dnName", "keyStoreFile",
		"keyStoreSecret" })
@Test(dependsOnMethods = "requestParameterMethodES384X509CertStep1")
public void requestParameterMethodES384X509CertStep2(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri, final String keyId, final String dnName,
		final String keyStoreFile, final String keyStoreSecret) throws Exception {
	Builder request = null;
	try {
		OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);
		List<String> scopes = Arrays.asList("openid");
		String nonce = UUID.randomUUID().toString();
		String state = UUID.randomUUID().toString();

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

		JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest,
				SignatureAlgorithm.ES384, cryptoProvider);
		jwtAuthorizationRequest.setKeyId(keyId);
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest
				.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
		jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE,
				ClaimValue.createValueList(new String[] { ACR_VALUE })));
		String authJwt = jwtAuthorizationRequest.getEncodedJwt();
		authorizationRequest.setRequest(authJwt);
		System.out.println("Request JWT: " + authJwt);

		request = ResteasyClientBuilder.newClient()
				.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
		request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
		request.header("Accept", MediaType.TEXT_PLAIN);
	} catch (Exception ex) {
		fail(ex.getMessage(), ex);
	}

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodES384X509CertStep2", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	try {
		URI uri = new URI(response.getLocation().toString());
		assertNotNull(uri.getFragment(), "Query string is null");

		Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

		assertNotNull(params.get("access_token"), "The accessToken is null");
		assertNotNull(params.get("scope"), "The scope is null");
		assertNotNull(params.get("state"), "The state is null");
	} catch (URISyntaxException e) {
		fail(e.getMessage(), e);
	}
}
 
Example 17
Source File: OpenIDRequestObjectWithESAlgEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri", "ES512_keyId", "dnName", "keyStoreFile",
		"keyStoreSecret" })
@Test(dependsOnMethods = "requestParameterMethodES512X509CertStep1")
public void requestParameterMethodES512X509CertStep2(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri, final String keyId, final String dnName,
		final String keyStoreFile, final String keyStoreSecret) throws Exception {
	Builder request = null;
	try {
		OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);
		List<String> scopes = Arrays.asList("openid");
		String nonce = UUID.randomUUID().toString();
		String state = UUID.randomUUID().toString();

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

		JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest,
				SignatureAlgorithm.ES512, cryptoProvider);
		jwtAuthorizationRequest.setKeyId(keyId);
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest
				.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
		jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE,
				ClaimValue.createValueList(new String[] { ACR_VALUE })));
		String authJwt = jwtAuthorizationRequest.getEncodedJwt();
		authorizationRequest.setRequest(authJwt);
		System.out.println("Request JWT: " + authJwt);

		request = ResteasyClientBuilder.newClient()
				.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
		request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
		request.header("Accept", MediaType.TEXT_PLAIN);
	} catch (Exception ex) {
		fail(ex.getMessage(), ex);
	}

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodES512X509CertStep2", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	try {
		URI uri = new URI(response.getLocation().toString());
		assertNotNull(uri.getFragment(), "Query string is null");

		Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

		assertNotNull(params.get("access_token"), "The accessToken is null");
		assertNotNull(params.get("scope"), "The scope is null");
		assertNotNull(params.get("state"), "The state is null");
	} catch (URISyntaxException e) {
		fail(e.getMessage(), e);
	}
}
 
Example 18
Source File: TTokenRequest.java    From oxAuth with MIT License 4 votes vote down vote up
private void requestAuthorizationCode(final String authorizePath, final String userId, final String userSecret,
		final String umaClientId, final String umaRedirectUri, final String p_scopeType) throws Exception {
	List<ResponseType> responseTypes = new ArrayList<ResponseType>();
	responseTypes.add(ResponseType.CODE);
	responseTypes.add(ResponseType.ID_TOKEN);

	List<String> scopes = new ArrayList<String>();
	scopes.add(p_scopeType);

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

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

	Builder request = ResteasyClientBuilder.newClient()
			.target(baseUri.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
	request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
	request.header("Accept", MediaType.TEXT_PLAIN);
	Response response = request.get();
	String entity = response.readEntity(String.class);

	BaseTest.showResponse("TTokenClient.requestAuthorizationCode() : ", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	if (response.getLocation() != null) {
		try {
			final String location = response.getLocation().toString();
			final int fragmentIndex = location.indexOf("#");

			Map<String, String> params = new HashMap<String, String>();
			if (fragmentIndex != -1) {
				String fragment = location.substring(fragmentIndex + 1);
				params = QueryStringDecoder.decode(fragment);
			} else {
				int queryStringIndex = location.indexOf("?");
				if (queryStringIndex != -1) {
					String queryString = location.substring(queryStringIndex + 1);
					params = QueryStringDecoder.decode(queryString);
				}
			}

			assertNotNull(params.get("code"), "The code is null");
			assertNotNull(params.get("scope"), "The scope is null");
			assertNotNull(params.get("state"), "The state is null");

			token.setAuthorizationCode(params.get("code"));
			token.setScope(params.get("scope"));
		} catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}
}
 
Example 19
Source File: ClientAuthenticationByAccessTokenHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret"})
@Test(dependsOnMethods = "requestClientRegistrationWithCustomAttributes")
public void requestAccessTokenCustomClientAuth1(final String userId, final String userSecret) throws Exception {
    showTitle("requestAccessTokenCustomClientAuth1");

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

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

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

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

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

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

    // 2. Validate code and id_token
    Jwt jwt = Jwt.parse(idToken);
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.CODE_HASH));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME));

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

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

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

    userAccessToken = tokenResponse.getAccessToken();
}