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

The following examples show how to use org.gluu.oxauth.client.AuthorizationRequest#setState() . 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: AccessTokenManualTest.java    From oxAuth with MIT License 6 votes vote down vote up
private AuthorizationResponse requestAuthorization(final String userId, final String userSecret, final String redirectUri,
                                                   List<ResponseType> responseTypes, List<String> scopes, String clientId, String nonce) {
    String state = UUID.randomUUID().toString();

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

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

    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");
    assertNotNull(authorizationResponse.getScope(), "The scope is null");
    return authorizationResponse;
}
 
Example 2
Source File: AuthorizationAction.java    From oxAuth with MIT License 5 votes vote down vote up
public String getOpenIdRequestObject() {
    openIdRequestObject = "";

    try {
        if (useOpenIdRequestObject) {
            AuthorizationRequest req = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
            req.setState(state);
            req.setRequestUri(requestUri);
            req.setMaxAge(maxAge);
            req.setUiLocales(StringUtils.spaceSeparatedToList(uiLocales));
            req.setClaimsLocales(StringUtils.spaceSeparatedToList(claimsLocales));
            req.setIdTokenHint(idTokenHint);
            req.setLoginHint(loginHint);
            req.setAcrValues(StringUtils.spaceSeparatedToList(acrValues));
            req.setRegistration(registration);
            req.setDisplay(display);
            req.getPrompts().addAll(prompt);

            OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
            JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(
                    req, SignatureAlgorithm.NONE, (String) null, cryptoProvider);
            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[]{"basic"})));
            jwtAuthorizationRequest.getIdTokenMember().setMaxAge(86400);
            openIdRequestObject = jwtAuthorizationRequest.getDecodedJwt();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return openIdRequestObject;
}
 
Example 3
Source File: SeleniumTestUtils.java    From oxd with Apache License 2.0 5 votes vote down vote up
private static String getAuthorizationUrl(String opHost, String clientId, String redirectUrls, String state, String nonce, List<String> responseTypes, List<String> scopes) {
    try {
        if(CollectionUtils.isEmpty(responseTypes)) {
            responseTypes = Lists.newArrayList("code", "id_token", "token");
        }

        if(CollectionUtils.isEmpty(scopes)) {
            scopes = Lists.newArrayList("openid", "profile", "oxd", "uma_protection");
        }
        List<ResponseType> resTypes = responseTypes.stream().map(item -> ResponseType.fromString(item)).collect(Collectors.toList());
        AuthorizationRequest authorizationRequest = new AuthorizationRequest(resTypes, clientId, scopes, redirectUrls.split(" ")[0], nonce);
        authorizationRequest.setResponseTypes(responseTypes.stream().map(item -> ResponseType.fromString(item)).collect(Collectors.toList()));
        authorizationRequest.setState(state);

        return URLDecoder.decode(opHost + "/oxauth/restv1/authorize?" +authorizationRequest.getQueryString(), Util.UTF8_STRING_ENCODING);

        /*return URLDecoder.decode(opHost + "/oxauth/restv1/authorize?" +
                "response_type=code+id_token+token" +
                "&state=" + state +
                "&nonce=" + nonce +
                "&client_id=" + clientId +
                "&redirect_uri=" + redirectUrls.split(" ")[0] +
                "&scope=openid+profile+oxd+uma_protection", Util.UTF8_STRING_ENCODING);*/
    } catch (UnsupportedEncodingException ex) {
        fail("Failed to decode the authorization URL.");
        return null;
    }
}
 
Example 4
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 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 = "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 6
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 7
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 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 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 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 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 10
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 11
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 12
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 13
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 14
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 15
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();
}
 
Example 16
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 17
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 18
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 19
Source File: AuthenticationFilter.java    From oxTrust with MIT License 4 votes vote down vote up
public String getOAuthRedirectUrl(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    String authorizeUrl = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_AUTHORIZE_URL, null);
    String clientScopes = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_SCOPE, null);

    String clientId = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_ID, null);
    String clientSecret = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, null);
    if (clientSecret != null) {
        try {
            clientSecret = StringEncrypter.defaultInstance().decrypt(clientSecret, Configuration.instance().getCryptoPropertyValue());
        } catch (EncryptionException ex) {
            log.error("Failed to decrypt property: " + Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, ex);
        }
    }

    String redirectUri = constructRedirectUrl(request);

    List<String> scopes = Arrays.asList(clientScopes.split(StringUtils.SPACE));
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);

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

    // Lookup for relying party ID
    final String key = request.getParameter(ExternalAuthentication.CONVERSATION_KEY);
    request.getSession().setAttribute(SESSION_CONVERSATION_KEY, key);
    ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, request);

    String relyingPartyId = "";
    final RelyingPartyContext relyingPartyCtx = prc.getSubcontext(RelyingPartyContext.class);
    if (relyingPartyCtx != null) {
        relyingPartyId = relyingPartyCtx.getRelyingPartyId();
        log.info("relyingPartyId found: " + relyingPartyId);
    } else
        log.warn("No RelyingPartyContext was available");

    // JWT
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    JwtState jwtState = new JwtState(SignatureAlgorithm.HS256, clientSecret, cryptoProvider);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    if (relyingPartyId != null && !"".equals(relyingPartyId)) {
        String additionalClaims = String.format("{relyingPartyId: '%s'}", relyingPartyId);
        jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
    } else
        log.warn("No relyingPartyId was available");
    String encodedState = jwtState.getEncodedJwt();

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

    Cookie currentShibstateCookie = getCurrentShibstateCookie(request);
    if (currentShibstateCookie != null) {
        String requestUri = decodeCookieValue(currentShibstateCookie.getValue());
        log.debug("requestUri = \"" + requestUri + "\"");

        String authenticationMode = determineAuthenticationMode(requestUri);

        if (StringHelper.isNotEmpty(authenticationMode)) {
            log.debug("acr_values = \"" + authenticationMode + "\"");
            authorizationRequest.setAcrValues(Arrays.asList(authenticationMode));
            updateShibstateCookie(response, currentShibstateCookie, requestUri, "/" + Configuration.OXAUTH_ACR_VALUES + "/" + authenticationMode);
        }
    }

    // Store for validation in session
    final HttpSession session = request.getSession(false);
    session.setAttribute(Configuration.SESSION_AUTH_STATE, encodedState);
    session.setAttribute(Configuration.SESSION_AUTH_NONCE, nonce);

    return authorizeUrl + "?" + authorizationRequest.getQueryString();
}
 
Example 20
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());
		}
	}
}