Search in sources :

Example 36 with Client

use of org.apache.cxf.rs.security.oauth2.common.Client 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 37 with Client

use of org.apache.cxf.rs.security.oauth2.common.Client 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 38 with Client

use of org.apache.cxf.rs.security.oauth2.common.Client in project meecrowave by apache.

the class JCacheConfigurer method doSetup.

public void doSetup(final OAuth2Options options) {
    if (!options.getProvider().startsWith("jcache")) {
        return;
    }
    provider = Caching.getCachingProvider();
    final File file = new File(options.getJcacheConfigUri());
    URI configFileURI = file.isFile() ? file.toURI() : null;
    if (configFileURI == null) {
        try {
            configFileURI = getClasspathResourceURL(options.getJcacheConfigUri(), JCacheOAuthDataProvider.class, bus).toURI();
        } catch (final Exception ex) {
            configFileURI = provider.getDefaultURI();
        }
    }
    cacheManager = provider.getCacheManager(configFileURI, Thread.currentThread().getContextClassLoader());
    try {
        cacheManager.createCache(JCacheOAuthDataProvider.CLIENT_CACHE_KEY, configure(new MutableConfiguration<String, Client>().setTypes(String.class, Client.class), options));
        if (!options.isJcacheStoreJwtKeyOnly()) /* && options.isUseJwtFormatForAccessTokens()*/
        {
            cacheManager.createCache(JCacheOAuthDataProvider.ACCESS_TOKEN_CACHE_KEY, configure(new MutableConfiguration<String, ServerAccessToken>().setTypes(String.class, ServerAccessToken.class), options));
        } else {
            cacheManager.createCache(JCacheOAuthDataProvider.ACCESS_TOKEN_CACHE_KEY, configure(new MutableConfiguration<String, String>().setTypes(String.class, String.class), options));
        }
        cacheManager.createCache(JCacheOAuthDataProvider.REFRESH_TOKEN_CACHE_KEY, configure(new MutableConfiguration<String, RefreshToken>().setTypes(String.class, RefreshToken.class), options));
        if (options.isAuthorizationCodeSupport()) {
            cacheManager.createCache(JCacheCodeDataProvider.CODE_GRANT_CACHE_KEY, configure(new MutableConfiguration<String, ServerAuthorizationCodeGrant>().setTypes(String.class, ServerAuthorizationCodeGrant.class), options));
        }
    } catch (final CacheException ce) {
    // already created
    }
}
Also used : CacheException(javax.cache.CacheException) URI(java.net.URI) CacheException(javax.cache.CacheException) ServerAccessToken(org.apache.cxf.rs.security.oauth2.common.ServerAccessToken) RefreshToken(org.apache.cxf.rs.security.oauth2.tokens.refresh.RefreshToken) ServerAuthorizationCodeGrant(org.apache.cxf.rs.security.oauth2.grants.code.ServerAuthorizationCodeGrant) Client(org.apache.cxf.rs.security.oauth2.common.Client) File(java.io.File)

Example 39 with Client

use of org.apache.cxf.rs.security.oauth2.common.Client in project cxf by apache.

the class AbstractTokenService method getClient.

protected Client getClient(String clientId, String clientSecret, MultivaluedMap<String, String> params) {
    if (clientId == null) {
        reportInvalidRequestError("Client ID is null");
        return null;
    }
    Client client = null;
    try {
        client = getValidClient(clientId, clientSecret, params);
    } catch (OAuthServiceException ex) {
        LOG.warning("No valid client found for clientId: " + clientId);
        if (ex.getError() != null) {
            reportInvalidClient(ex.getError());
            return null;
        }
    }
    if (client == null) {
        LOG.warning("No valid client found for clientId: " + clientId);
        reportInvalidClient();
    }
    return client;
}
Also used : OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) Client(org.apache.cxf.rs.security.oauth2.common.Client)

Example 40 with Client

use of org.apache.cxf.rs.security.oauth2.common.Client in project cxf by apache.

the class AccessTokenService method handleTokenRequest.

/**
 * Processes an access token request
 * @param params the form parameters representing the access token grant
 * @return Access Token or the error
 */
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Response handleTokenRequest(MultivaluedMap<String, String> params) {
    // Make sure the client is authenticated
    Client client = authenticateClientIfNeeded(params);
    if (!OAuthUtils.isGrantSupportedForClient(client, isCanSupportPublicClients(), params.getFirst(OAuthConstants.GRANT_TYPE))) {
        LOG.log(Level.FINE, "The grant type {} is not supported for the client", params.getFirst(OAuthConstants.GRANT_TYPE));
        return createErrorResponse(params, OAuthConstants.UNAUTHORIZED_CLIENT);
    }
    try {
        checkAudience(client, params);
    } catch (OAuthServiceException ex) {
        return super.createErrorResponseFromBean(ex.getError());
    }
    // Find the grant handler
    AccessTokenGrantHandler handler = findGrantHandler(params);
    if (handler == null) {
        LOG.fine("No Grant Handler found");
        return createErrorResponse(params, OAuthConstants.UNSUPPORTED_GRANT_TYPE);
    }
    // Create the access token
    final ServerAccessToken serverToken;
    try {
        serverToken = handler.createAccessToken(client, params);
    } catch (WebApplicationException ex) {
        throw ex;
    } catch (RuntimeException ex) {
        LOG.log(Level.FINE, "Error creating the access token", ex);
        // This is done to bypass a Check-Style
        // restriction on a number of return statements
        OAuthServiceException oauthEx = ex instanceof OAuthServiceException ? (OAuthServiceException) ex : new OAuthServiceException(ex);
        return handleException(oauthEx, OAuthConstants.INVALID_GRANT);
    }
    if (serverToken == null) {
        LOG.fine("No access token was created");
        return createErrorResponse(params, OAuthConstants.INVALID_GRANT);
    }
    // Extract the information to be of use for the client
    ClientAccessToken clientToken = OAuthUtils.toClientAccessToken(serverToken, isWriteOptionalParameters());
    processClientAccessToken(clientToken, serverToken);
    // Return it to the client
    return Response.ok(clientToken).header(HttpHeaders.CACHE_CONTROL, "no-store").header("Pragma", "no-cache").build();
}
Also used : ServerAccessToken(org.apache.cxf.rs.security.oauth2.common.ServerAccessToken) WebApplicationException(javax.ws.rs.WebApplicationException) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) AccessTokenGrantHandler(org.apache.cxf.rs.security.oauth2.provider.AccessTokenGrantHandler) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) Client(org.apache.cxf.rs.security.oauth2.common.Client) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

WebClient (org.apache.cxf.jaxrs.client.WebClient)112 ClientAccessToken (org.apache.cxf.rs.security.oauth2.common.ClientAccessToken)100 Response (javax.ws.rs.core.Response)79 Client (org.apache.cxf.rs.security.oauth2.common.Client)75 Form (javax.ws.rs.core.Form)64 URL (java.net.URL)59 OAuthAuthorizationData (org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)36 ServerAccessToken (org.apache.cxf.rs.security.oauth2.common.ServerAccessToken)36 Test (org.junit.Test)35 OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)27 UserSubject (org.apache.cxf.rs.security.oauth2.common.UserSubject)25 AccessTokenRegistration (org.apache.cxf.rs.security.oauth2.common.AccessTokenRegistration)22 OAuthPermission (org.apache.cxf.rs.security.oauth2.common.OAuthPermission)21 JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)16 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)15 ArrayList (java.util.ArrayList)13 TokenIntrospection (org.apache.cxf.rs.security.oauth2.common.TokenIntrospection)12 RefreshToken (org.apache.cxf.rs.security.oauth2.tokens.refresh.RefreshToken)12 Book (org.apache.cxf.systest.jaxrs.security.Book)11 Consumes (javax.ws.rs.Consumes)8