use of org.apache.cxf.rs.security.oauth2.common.ClientAccessToken in project testcases by coheigea.
the class HybridFlowTest method testCodeIdToken.
@org.junit.Test
public void testCodeIdToken() throws Exception {
URL busFile = HybridFlowTest.class.getResource("cxf-client.xml");
String address = "https://localhost:" + PORT + "/services/";
WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
// Get location
String location = getLocation(client, "openid", "code id_token");
assertNotNull(location);
// Check code
String code = getSubstring(location, "code");
assertNotNull(code);
// Check id_token
String idToken = getSubstring(location, "id_token");
assertNotNull(idToken);
validateIdToken(idToken, "123456789");
// Now get the access token
client = WebClient.create(address, setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(client, code);
assertNotNull(accessToken.getTokenKey());
assertTrue(accessToken.getApprovedScope().contains("openid"));
// Check id_token from the token endpoint
idToken = accessToken.getParameters().get("id_token");
assertNotNull(idToken);
validateIdToken(idToken, null);
}
use of org.apache.cxf.rs.security.oauth2.common.ClientAccessToken in project ddf by codice.
the class OAuthPlugin method refreshTokens.
/**
* Attempts to refresh the user's access token and saves the new tokens in the token storage
*
* @param refreshToken refresh token used to refresh access token
* @param oauthSource source being queried
* @throws OAuthPluginException if the access token could not be renewed
*/
private void refreshTokens(String refreshToken, OAuthFederatedSource oauthSource, String sessionId, OIDCProviderMetadata metadata) throws StopProcessingException {
if (refreshToken == null) {
throw createNoAuthException(oauthSource, sessionId, metadata, "unable to find the user's refresh token.");
}
ClientAccessToken clientAccessToken;
try {
LOGGER.debug("Attempting to refresh the user's access token.");
WebClient webClient = createWebclient(metadata.getTokenEndpointURI().toURL().toString());
Consumer consumer = new Consumer(oauthSource.getOauthClientId(), oauthSource.getOauthClientSecret());
AccessTokenGrant accessTokenGrant = new RefreshTokenGrant(refreshToken);
clientAccessToken = OAuthClientUtils.getAccessToken(webClient, consumer, accessTokenGrant);
} catch (OAuthServiceException e) {
String error = e.getError() != null ? e.getError().getError() : "";
throw createNoAuthException(oauthSource, sessionId, metadata, "failed to refresh access token " + error);
} catch (MalformedURLException e) {
throw createNoAuthException(oauthSource, sessionId, metadata, "malformed token endpoint URL. " + e.getMessage());
}
// Validate new access token
try {
AccessToken accessToken = convertCxfAccessTokenToNimbusdsToken(clientAccessToken);
OidcTokenValidator.validateAccessToken(accessToken, null, resourceRetriever, metadata, null);
} catch (OidcValidationException e) {
throw createNoAuthException(oauthSource, sessionId, metadata, "failed to validate refreshed access token.");
}
// Store new tokens
String newAccessToken = clientAccessToken.getTokenKey();
String newRefreshToken = clientAccessToken.getRefreshToken();
int status = tokenStorage.create(sessionId, oauthSource.getId(), newAccessToken, newRefreshToken, oauthSource.getOauthDiscoveryUrl());
if (status != SC_OK) {
LOGGER.warn("Error updating the token information.");
}
}
use of org.apache.cxf.rs.security.oauth2.common.ClientAccessToken in project meecrowave by apache.
the class OAuth2Test method getPasswordTokenNoClient.
@Test
public void getPasswordTokenNoClient() {
final Client client = ClientBuilder.newClient().register(new OAuthJSONProvider());
try {
final ClientAccessToken token = client.target("http://localhost:" + MEECROWAVE.getConfiguration().getHttpPort()).path("oauth2/token").request(APPLICATION_JSON_TYPE).post(entity(new Form().param("grant_type", "password").param("username", "test").param("password", "pwd"), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class);
assertNotNull(token);
assertEquals("Bearer", token.getTokenType());
assertNotNull(token.getTokenKey());
assertIsJwt(token.getTokenKey(), "__default");
assertEquals(3600, token.getExpiresIn());
assertNotEquals(0, token.getIssuedAt());
assertNotNull(token.getRefreshToken());
validateJwt(token);
} finally {
client.close();
}
}
use of org.apache.cxf.rs.security.oauth2.common.ClientAccessToken in project meecrowave by apache.
the class OAuth2Test method authorizationCode.
@Test
public void authorizationCode() throws URISyntaxException {
final int httpPort = MEECROWAVE.getConfiguration().getHttpPort();
createRedirectedClient(httpPort);
final Client client = ClientBuilder.newClient().property(Message.MAINTAIN_SESSION, true).register(new OAuthJSONProvider());
try {
final WebTarget target = client.target("http://localhost:" + httpPort);
final Response authorization = target.path("oauth2/authorize").queryParam(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE_GRANT).queryParam(OAuthConstants.RESPONSE_TYPE, OAuthConstants.CODE_RESPONSE_TYPE).queryParam(OAuthConstants.CLIENT_ID, "c1").queryParam(OAuthConstants.CLIENT_SECRET, "cpwd").queryParam(OAuthConstants.REDIRECT_URI, "http://localhost:" + httpPort + "/redirected").request(APPLICATION_JSON_TYPE).header("authorization", "Basic " + Base64.getEncoder().encodeToString("test:pwd".getBytes(StandardCharsets.UTF_8))).get();
final OAuthAuthorizationData data = authorization.readEntity(OAuthAuthorizationData.class);
assertNotNull(data.getAuthenticityToken());
assertEquals("c1", data.getClientId());
assertEquals("http://localhost:" + httpPort + "/oauth2/authorize/decision", data.getReplyTo());
assertEquals("code", data.getResponseType());
assertEquals("http://localhost:" + httpPort + "/redirected", data.getRedirectUri());
final Response decision = target.path("oauth2/authorize/decision").queryParam(OAuthConstants.SESSION_AUTHENTICITY_TOKEN, data.getAuthenticityToken()).queryParam(OAuthConstants.AUTHORIZATION_DECISION_KEY, "allow").request(APPLICATION_JSON_TYPE).cookie(authorization.getCookies().get("JSESSIONID")).header("authorization", "Basic " + Base64.getEncoder().encodeToString("test:pwd".getBytes(StandardCharsets.UTF_8))).get();
assertEquals(Response.Status.SEE_OTHER.getStatusCode(), decision.getStatus());
assertTrue(decision.getLocation().toASCIIString(), decision.getLocation().toASCIIString().startsWith("http://localhost:" + httpPort + "/redirected?code="));
final ClientAccessToken token = target.path("oauth2/token").request(APPLICATION_JSON_TYPE).post(entity(new Form().param(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE_GRANT).param(OAuthConstants.CODE_RESPONSE_TYPE, decision.getLocation().getRawQuery().substring("code=".length())).param(OAuthConstants.REDIRECT_URI, "http://localhost:" + httpPort + "/redirected").param(OAuthConstants.CLIENT_ID, "c1").param(OAuthConstants.CLIENT_SECRET, "cpwd"), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class);
assertNotNull(token);
assertEquals("Bearer", token.getTokenType());
assertIsJwt(token.getTokenKey(), "c1");
assertEquals(3600, token.getExpiresIn());
assertNotEquals(0, token.getIssuedAt());
assertNotNull(token.getRefreshToken());
} finally {
client.close();
}
}
use of org.apache.cxf.rs.security.oauth2.common.ClientAccessToken in project meecrowave by apache.
the class OAuth2Test method validateJwt.
private void validateJwt(final ClientAccessToken token) {
final JwtParser parser = new JwtParser();
final KidMapper kidMapper = new KidMapper();
final DateValidator dateValidator = new DateValidator();
final SignatureValidator signatureValidator = new SignatureValidator();
final GeronimoJwtAuthConfig config = (value, def) -> {
switch(value) {
case "issuer.default":
return "myissuer";
case "jwt.header.kid.default":
return "defaultkid";
case "public-key.default":
return Base64.getEncoder().encodeToString(PUBLIC_KEY.getEncoded());
default:
return def;
}
};
setField(kidMapper, "config", config);
setField(dateValidator, "config", config);
setField(parser, "config", config);
setField(signatureValidator, "config", config);
setField(parser, "kidMapper", kidMapper);
setField(parser, "dateValidator", dateValidator);
setField(parser, "signatureValidator", signatureValidator);
Stream.of(dateValidator, signatureValidator, kidMapper, parser).forEach(this::init);
final JsonWebToken jsonWebToken = parser.parse(token.getTokenKey());
assertNotNull(jsonWebToken);
assertEquals("myissuer", jsonWebToken.getIssuer());
assertEquals("test", JsonString.class.cast(jsonWebToken.getClaim("username")).getString());
}
Aggregations