Search in sources :

Example 16 with ClientAccessToken

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);
}
Also used : ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL)

Example 17 with ClientAccessToken

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.");
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Consumer(org.apache.cxf.rs.security.oauth2.client.Consumer) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) RefreshTokenGrant(org.apache.cxf.rs.security.oauth2.grants.refresh.RefreshTokenGrant) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) TypelessAccessToken(com.nimbusds.oauth2.sdk.token.TypelessAccessToken) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) AccessTokenGrant(org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant) WebClient(org.apache.cxf.jaxrs.client.WebClient) OidcValidationException(org.codice.ddf.security.oidc.validator.OidcValidationException)

Example 18 with ClientAccessToken

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();
    }
}
Also used : Form(javax.ws.rs.core.Form) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) Client(javax.ws.rs.client.Client) Test(org.junit.Test)

Example 19 with ClientAccessToken

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();
    }
}
Also used : Response(javax.ws.rs.core.Response) Form(javax.ws.rs.core.Form) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData) Test(org.junit.Test)

Example 20 with ClientAccessToken

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());
}
Also used : JwtParser(org.apache.geronimo.microprofile.impl.jwtauth.jwt.JwtParser) KidMapper(org.apache.geronimo.microprofile.impl.jwtauth.jwt.KidMapper) DateValidator(org.apache.geronimo.microprofile.impl.jwtauth.jwt.DateValidator) URISyntaxException(java.net.URISyntaxException) BiFunction(java.util.function.BiFunction) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) Collections.singletonList(java.util.Collections.singletonList) Cache(javax.cache.Cache) JCacheCodeDataProvider(org.apache.meecrowave.oauth2.provider.JCacheCodeDataProvider) MutableConfiguration(javax.cache.configuration.MutableConfiguration) Assert.fail(org.junit.Assert.fail) ClassRule(org.junit.ClassRule) Method(java.lang.reflect.Method) JsonObject(javax.json.JsonObject) JsonbBuilder(javax.json.bind.JsonbBuilder) APPLICATION_FORM_URLENCODED_TYPE(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED_TYPE) MeecrowaveRule(org.apache.meecrowave.junit.MeecrowaveRule) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) CachingProvider(javax.cache.spi.CachingProvider) StandardCharsets(java.nio.charset.StandardCharsets) DateValidator(org.apache.geronimo.microprofile.impl.jwtauth.jwt.DateValidator) Base64(java.util.Base64) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) GeronimoJwtAuthConfig(org.apache.geronimo.microprofile.impl.jwtauth.config.GeronimoJwtAuthConfig) CacheManager(javax.cache.CacheManager) Meecrowave(org.apache.meecrowave.Meecrowave) JwtParser(org.apache.geronimo.microprofile.impl.jwtauth.jwt.JwtParser) BeforeClass(org.junit.BeforeClass) Form(javax.ws.rs.core.Form) Client(javax.ws.rs.client.Client) Entity.entity(javax.ws.rs.client.Entity.entity) ClientBuilder(javax.ws.rs.client.ClientBuilder) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData) SignatureValidator(org.apache.geronimo.microprofile.impl.jwtauth.jwt.SignatureValidator) Message(org.apache.cxf.message.Message) Assert.assertNotNull(org.junit.Assert.assertNotNull) Caching(javax.cache.Caching) KidMapper(org.apache.geronimo.microprofile.impl.jwtauth.jwt.KidMapper) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) PublicKey(java.security.PublicKey) ClassLoaderUtils(org.apache.cxf.common.classloader.ClassLoaderUtils) Field(java.lang.reflect.Field) File(java.io.File) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) JsonString(javax.json.JsonString) JsonWebToken(org.eclipse.microprofile.jwt.JsonWebToken) OAuthConstants(org.apache.cxf.rs.security.oauth2.utils.OAuthConstants) APPLICATION_JSON_TYPE(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE) Jsonb(javax.json.bind.Jsonb) WebTarget(javax.ws.rs.client.WebTarget) Assert.assertEquals(org.junit.Assert.assertEquals) SignatureValidator(org.apache.geronimo.microprofile.impl.jwtauth.jwt.SignatureValidator) GeronimoJwtAuthConfig(org.apache.geronimo.microprofile.impl.jwtauth.config.GeronimoJwtAuthConfig) JsonWebToken(org.eclipse.microprofile.jwt.JsonWebToken)

Aggregations

ClientAccessToken (org.apache.cxf.rs.security.oauth2.common.ClientAccessToken)134 WebClient (org.apache.cxf.jaxrs.client.WebClient)116 URL (java.net.URL)53 Response (javax.ws.rs.core.Response)51 Form (javax.ws.rs.core.Form)41 Test (org.junit.Test)21 Consumer (org.apache.cxf.rs.security.oauth2.client.Consumer)16 Book (org.apache.cxf.systest.jaxrs.security.Book)12 JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)11 TokenIntrospection (org.apache.cxf.rs.security.oauth2.common.TokenIntrospection)11 OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)8 JsonMapObjectProvider (org.apache.cxf.jaxrs.provider.json.JsonMapObjectProvider)7 OAuthJSONProvider (org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider)7 ClientRegistration (org.apache.cxf.rs.security.oauth2.services.ClientRegistration)7 ClientRegistrationResponse (org.apache.cxf.rs.security.oauth2.services.ClientRegistrationResponse)7 ResponseProcessingException (javax.ws.rs.client.ResponseProcessingException)6 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)6 AuthorizationCodeGrant (org.apache.cxf.rs.security.oauth2.grants.code.AuthorizationCodeGrant)6 HashMap (java.util.HashMap)4 Produces (javax.ws.rs.Produces)4