下面列出了javax.ws.rs.client.Invocation.Builder#header ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Parameters({"tokenPath", "userId", "userSecret", "audience"})
@Test
public void requestAccessTokenWithClientSecretJwtFail(final String tokenPath, final String userId,
final String userSecret, final String audience) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();
request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
tokenRequest.setUsername(userId);
tokenRequest.setPassword(userSecret);
tokenRequest.setScope("email read_stream manage_pages");
tokenRequest.setAuthPassword("INVALID_SECRET");
tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
tokenRequest.setAudience(audience);
Response response = request
.post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
String entity = response.readEntity(String.class);
showResponse("requestAccessTokenWithClientSecretJwt Fail", response, entity);
assertEquals(response.getStatus(), 401, "Unexpected response code.");
assertNotNull(entity, "Unexpected result: " + entity);
try {
JSONObject jsonObj = new JSONObject(entity);
assertTrue(jsonObj.has("error"), "The error type is null");
assertTrue(jsonObj.has("error_description"), "The error description is null");
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
@Parameters({"userInfoPath"})
@Test(dependsOnMethods = "revokeTokensStep4")
public void revokeTokensStep5(final String userInfoPath) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + userInfoPath).request();
request.header("Authorization", "Bearer " + accessToken1);
UserInfoRequest userInfoRequest = new UserInfoRequest(null);
Response response = request
.post(Entity.form(new MultivaluedHashMap<String, String>(userInfoRequest.getParameters())));
String entity = response.readEntity(String.class);
showResponse("revokeTokensStep5", response, entity);
assertEquals(response.getStatus(), 401, "Unexpected response code.");
assertNotNull(entity, "Unexpected result: " + entity);
try {
JSONObject jsonObj = new JSONObject(entity);
assertTrue(jsonObj.has("error"), "The error type is null");
assertTrue(jsonObj.has("error_description"), "The error description is null");
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
@Parameters({ "umaScopePath" })
@Test
public void scopePresence(final String umaScopePath) throws Exception {
String path = umaScopePath + "/" + "modify";
System.out.println("Path: " + path);
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + path).request();
request.header("Accept", UmaConstants.JSON_MEDIA_TYPE);
Response response = request.get();
String entity = response.readEntity(String.class);
BaseTest.showResponse("UMA : UmaScopeWSTest.scopePresence() : ", response, entity);
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Unexpected response code.");
final UmaScopeDescription scope = TUma.readJsonValue(entity, UmaScopeDescription.class);
UmaTestUtil.assert_(scope);
}
/**
* Read client to check whether it is using the Token Endpoint Auth Method
* <code>client_secret_basic</code>.
*/
@Parameters({"registerPath"})
@Test(dependsOnMethods = "tokenEndpointAuthMethodClientSecretBasicStep1")
public void tokenEndpointAuthMethodClientSecretBasicStep2(final String registerPath) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath + "?"
+ registrationClientUri2.substring(registrationClientUri2.indexOf("?") + 1)).request();
request.header("Authorization", "Bearer " + registrationAccessToken2);
Response response = request.get();
String entity = response.readEntity(String.class);
showResponse("tokenEndpointAuthMethodClientSecretBasicStep2", response, entity);
assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
assertNotNull(entity, "Unexpected result: " + entity);
try {
JSONObject jsonObj = new JSONObject(entity);
assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));
// Registered Metadata
assertTrue(jsonObj.has(TOKEN_ENDPOINT_AUTH_METHOD.toString()));
assertEquals(jsonObj.getString(TOKEN_ENDPOINT_AUTH_METHOD.toString()),
AuthenticationMethod.CLIENT_SECRET_BASIC.toString());
assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
assertTrue(jsonObj.has(RESPONSE_TYPES.toString()));
assertTrue(jsonObj.has(REDIRECT_URIS.toString()));
assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
assertTrue(jsonObj.has(CLIENT_NAME.toString()));
assertTrue(jsonObj.has(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
assertTrue(jsonObj.has(SCOPE.toString()));
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
@Parameters({"authorizePath", "userId", "userSecret"})
@Test
public void requestAuthorizationCodeFail1(final String authorizePath, final String userId, final String userSecret)
throws Exception {
// Testing with missing parameters
AuthorizationRequest authorizationRequest = new AuthorizationRequest(null, null, null, null, null);
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("requestAuthorizationCodeFail1", response, entity);
assertEquals(response.getStatus(), 400, "Unexpected response code.");
assertNotNull(entity, "Unexpected result: " + entity);
try {
JSONObject jsonObj = new JSONObject(entity);
assertTrue(jsonObj.has("error"), "The error type is null");
assertTrue(jsonObj.has("error_description"), "The error description is null");
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
private Response processRequest(String url, String method, String payload, String authHeader) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Builder builder = target.request();
builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
if (authHeader != null) {
builder.header(HttpHeaders.AUTHORIZATION, authHeader);
}
return (payload != null) ? builder.build(method, Entity.json(payload)).invoke()
: builder.build(method).invoke();
}
public void checkSubscription(String subscriptionId, String accessToken) throws InteractiveLoginException {
if (subscriptionId == null) {
throw new InteractiveLoginException("Parameter subscriptionId is required and cannot be null.");
}
Client client = ClientBuilder.newClient();
WebTarget resource = client.target(AZURE_MANAGEMENT);
Builder request = resource.path("/subscriptions/" + subscriptionId)
.queryParam("api-version", "2016-06-01")
.request();
request.accept(MediaType.APPLICATION_JSON);
request.header("Authorization", "Bearer " + accessToken);
try (Response response = request.get()) {
if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
AzureSubscription subscription = response.readEntity(AzureSubscription.class);
if (!subscription.getState().equals(SubscriptionState.ENABLED)) {
throw new InteractiveLoginException("Subscription is in incorrect state:" + "" + subscription.getState());
}
LOGGER.debug("Subscription definitions successfully retrieved:" + subscription.getDisplayName());
} else {
String errorResponse = response.readEntity(String.class);
try {
String errorMessage = new ObjectMapper().readTree(errorResponse).get("error").get("message").asText();
LOGGER.info("Subscription retrieve error:" + errorMessage);
throw new InteractiveLoginException("Error with the subscription id: " + subscriptionId + " message: " + errorMessage);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
}
public Response processRequest(String url, String method, String payload, String authHeader) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Builder builder = target.request();
builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
if (authHeader != null) {
builder.header(HttpHeaders.AUTHORIZATION, authHeader);
}
return (payload != null)
? builder.build(method, Entity.json(payload)).invoke()
: builder.build(method).invoke();
}
@Parameters({"clientInfoPath"})
@Test
public void requestClientInfoInvalidRequest(final String clientInfoPath) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + clientInfoPath).request();
request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
ClientInfoRequest clientInfoRequest = new ClientInfoRequest(null);
Response response = request
.post(Entity.form(new MultivaluedHashMap<String, String>(clientInfoRequest.getParameters())));
String entity = response.readEntity(String.class);
showResponse("requestClientInfoInvalidRequest", response, entity);
assertEquals(response.getStatus(), 400, "Unexpected response code.");
assertNotNull(entity, "Unexpected result: " + entity);
try {
JSONObject jsonObj = new JSONObject(entity);
assertTrue(jsonObj.has("error"), "The error type is null");
assertTrue(jsonObj.has("error_description"), "The error description is null");
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
/**
* Fail 1: Call to Token Endpoint with Auth Method
* <code>client_secret_post</code> should fail.
*/
@Parameters({"tokenPath", "userId", "userSecret"})
@Test(dependsOnMethods = "tokenEndpointAuthMethodClientSecretBasicStep2")
public void tokenEndpointAuthMethodClientSecretBasicFail1(final String tokenPath, final String userId,
final String userSecret) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();
TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);
tokenRequest.setUsername(userId);
tokenRequest.setPassword(userSecret);
tokenRequest.setScope("email read_stream manage_pages");
tokenRequest.setAuthUsername(clientId2);
tokenRequest.setAuthPassword(clientSecret2);
request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
Response response = request
.post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
String entity = response.readEntity(String.class);
showResponse("tokenEndpointAuthMethodClientSecretBasicFail1", response, entity);
assertEquals(response.getStatus(), 401, "Unexpected response code.");
assertNotNull(entity, "Unexpected result: " + entity);
try {
JSONObject jsonObj = new JSONObject(entity);
assertTrue(jsonObj.has("error"), "The error type is null");
assertTrue(jsonObj.has("error_description"), "The error description is null");
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
@Test
public void testGetPodcasts() throws JsonGenerationException,
JsonMappingException, IOException {
ClientConfig clientConfig = new ClientConfig();
clientConfig.register(JacksonFeature.class);
Client client = ClientBuilder.newClient(clientConfig);
WebTarget webTarget = client
.target("http://localhost:8888/demo-rest-spring-jersey-tomcat-mybatis-0.0.1-SNAPSHOT/podcasts/");
Builder request = webTarget.request();
request.header("Content-type", MediaType.APPLICATION_JSON);
Response response = request.get();
Assert.assertTrue(response.getStatus() == 200);
List<Podcast> podcasts = response
.readEntity(new GenericType<List<Podcast>>() {
});
ObjectMapper mapper = new ObjectMapper();
System.out.print(mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(podcasts));
Assert.assertTrue("At least one podcast is present",
podcasts.size() > 0);
}
private void addAuthorizations(Builder request, String userId, MultivaluedMap<String, Object> myHeaders) throws Exception {
logger.debug("Adding auth for user " + userId);
String encodedBytes = Base64.encode(userId.getBytes("UTF-8"));
request.header("Authorization", "Direct " + encodedBytes);
myHeaders.add("Authorization", "Direct " + encodedBytes);
}
/**
* 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());
}
}
/**
* Read client to check whether it is using the default Application Type
* <code>web</code>.
*/
@Parameters({"registerPath"})
@Test(dependsOnMethods = "omittedApplicationTypeStep1")
public void omittedApplicationTypeStep2(final String registerPath) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath + "?"
+ registrationClientUri1.substring(registrationClientUri1.indexOf("?") + 1)).request();
request.header("Authorization", "Bearer " + registrationAccessToken1);
Response response = request.get();
String entity = response.readEntity(String.class);
showResponse("omittedApplicationTypeStep2", response, entity);
assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
assertNotNull(entity, "Unexpected result: " + entity);
try {
JSONObject jsonObj = new JSONObject(entity);
assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));
// Registered Metadata
assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
assertEquals(jsonObj.getString(APPLICATION_TYPE.toString()), ApplicationType.WEB.toString());
assertTrue(jsonObj.has(RESPONSE_TYPES.toString()));
assertNotNull(jsonObj.optJSONArray(RESPONSE_TYPES.toString()));
assertEquals(jsonObj.getJSONArray(RESPONSE_TYPES.toString()).getString(0), ResponseType.CODE.toString());
assertTrue(jsonObj.has(REDIRECT_URIS.toString()));
assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
assertTrue(jsonObj.has(CLIENT_NAME.toString()));
assertTrue(jsonObj.has(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
assertTrue(jsonObj.has(SCOPE.toString()));
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
@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");
}
}
@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);
}
}
@Parameters({"authorizePath", "redirectUri"})
@Test(dependsOnMethods = "requestAuthorizationAccessTokenStep1", enabled = false)
public void requestAuthorizationAccessTokenFail(final String authorizePath, 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, clientId1, scopes,
redirectUri, null);
authorizationRequest.setState(state);
authorizationRequest.getPrompts().add(Prompt.NONE);
authorizationRequest.setAccessToken("INVALID_ACCESS_TOKEN");
Builder request = ResteasyClientBuilder.newClient()
.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
request.header("Accept", MediaType.TEXT_PLAIN);
Response response = request.get();
String entity = response.readEntity(String.class);
showResponse("requestAuthorizationAccessTokenFail", 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(), "The query string is null");
Map<String, String> params = QueryStringDecoder.decode(uri.getQuery());
assertNotNull(params.get("error"), "The error value is null");
assertNotNull(params.get("error_description"), "The errorDescription value 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");
}
}
}
@Parameters({"authorizePath", "userId", "userSecret", "redirectUri"})
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestAuthorizationCodeIdToken(final String authorizePath, final String userId,
final String userSecret, final String redirectUri) throws Exception {
final String state = UUID.randomUUID().toString();
final String nonce = UUID.randomUUID().toString();
List<ResponseType> responseTypes = new ArrayList<ResponseType>();
responseTypes.add(ResponseType.CODE);
responseTypes.add(ResponseType.ID_TOKEN);
List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId1, scopes,
redirectUri, nonce);
authorizationRequest.setState(state);
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("requestAuthorizationCodeIdToken", 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(AuthorizeResponseParam.CODE), "The code is null");
assertNotNull(params.get(AuthorizeResponseParam.ID_TOKEN), "The id token 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");
}
}
@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");
}
}
}
@Parameters({"authorizePath", "userId", "userSecret", "redirectUri"})
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestAuthorizationPromptNoneLoginConsentFail(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, clientId1, scopes,
redirectUri, null);
authorizationRequest.setState(state);
authorizationRequest.getPrompts().add(Prompt.NONE);
authorizationRequest.getPrompts().add(Prompt.LOGIN);
authorizationRequest.getPrompts().add(Prompt.CONSENT);
authorizationRequest.setAuthUsername(userId);
authorizationRequest.setAuthPassword(userSecret);
Builder request = ResteasyClientBuilder.newClient()
.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
Response response = request.get();
String entity = response.readEntity(String.class);
showResponse("requestAuthorizationPromptNoneLoginConsentFail", 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("error"), "The error value is null");
assertNotNull(params.get("error_description"), "The errorDescription value 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");
}
}
}