Search in sources :

Example 1 with Consumer

use of org.apache.cxf.rs.security.oauth2.client.Consumer in project camel by apache.

the class OAuthToken method getOrRefreshAccessToken.

private synchronized void getOrRefreshAccessToken() {
    if (token == null) {
        LOGGER.debug("Generate OAuth token");
        token = OAuthClientUtils.getAccessToken(WebClient.create(configuration.getOauthTokenUrl()), new Consumer(configuration.getOauthClientId(), configuration.getOauthClientSecret()), new ResourceOwnerGrant(configuration.getUserName(), configuration.getPassword()), true);
        LOGGER.debug("OAuth token expires in {}s", token.getExpiresIn());
        // Set expiration time related info in milliseconds
        token.setIssuedAt(System.currentTimeMillis());
        token.setExpiresIn(TimeUnit.MILLISECONDS.convert(token.getExpiresIn(), TimeUnit.SECONDS));
        authString = token.toString();
        if (token.getExpiresIn() > 0) {
            expireAt = token.getIssuedAt() + token.getExpiresIn();
        }
    } else if (expireAt > 0 && System.currentTimeMillis() >= expireAt) {
        LOGGER.debug("OAuth token is expired, refresh it");
        token = OAuthClientUtils.refreshAccessToken(WebClient.create(configuration.getOauthTokenUrl()), new Consumer(configuration.getOauthClientId(), configuration.getOauthClientSecret()), token, null, false);
        LOGGER.debug("Refreshed OAuth token expires in {}s", token.getExpiresIn());
        // Set expiration time related info in milliseconds
        token.setIssuedAt(System.currentTimeMillis());
        token.setExpiresIn(TimeUnit.MILLISECONDS.convert(token.getExpiresIn(), TimeUnit.SECONDS));
        authString = token.toString();
        if (token.getExpiresIn() > 0) {
            expireAt = token.getIssuedAt() + token.getExpiresIn();
        }
    }
}
Also used : Consumer(org.apache.cxf.rs.security.oauth2.client.Consumer) ResourceOwnerGrant(org.apache.cxf.rs.security.oauth2.grants.owner.ResourceOwnerGrant)

Example 2 with Consumer

use of org.apache.cxf.rs.security.oauth2.client.Consumer in project cxf by apache.

the class OAuthClientUtils method getAccessToken.

/**
 * Obtains the access token from OAuth AccessToken Service
 * using the initialized web client
 * @param accessTokenService the AccessToken client
 * @param consumer {@link Consumer} representing the registered client.
 * @param grant {@link AccessTokenGrant} grant
 * @param extraParams extra parameters
 * @param defaultTokenType default expected token type - some early
 *        well-known OAuth2 services do not return a required token_type parameter
 * @param setAuthorizationHeader if set to true then HTTP Basic scheme
 *           will be used to pass client id and secret, otherwise they will
 *           be passed in the form payload
 * @return {@link ClientAccessToken} access token
 * @throws OAuthServiceException
 */
public static ClientAccessToken getAccessToken(WebClient accessTokenService, Consumer consumer, AccessTokenGrant grant, Map<String, String> extraParams, String defaultTokenType, boolean setAuthorizationHeader) throws OAuthServiceException {
    if (accessTokenService == null) {
        throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
    }
    Form form = new Form(grant.toMap());
    if (extraParams != null) {
        for (Map.Entry<String, String> entry : extraParams.entrySet()) {
            form.param(entry.getKey(), entry.getValue());
        }
    }
    if (consumer != null) {
        boolean secretAvailable = !StringUtils.isEmpty(consumer.getClientSecret());
        if (setAuthorizationHeader && secretAvailable) {
            StringBuilder sb = new StringBuilder();
            sb.append("Basic ");
            try {
                String data = consumer.getClientId() + ":" + consumer.getClientSecret();
                sb.append(Base64Utility.encode(data.getBytes(StandardCharsets.UTF_8)));
            } catch (Exception ex) {
                throw new ProcessingException(ex);
            }
            accessTokenService.replaceHeader("Authorization", sb.toString());
        } else {
            form.param(OAuthConstants.CLIENT_ID, consumer.getClientId());
            if (secretAvailable) {
                form.param(OAuthConstants.CLIENT_SECRET, consumer.getClientSecret());
            }
        }
    } else {
    // in this case the AccessToken service is expected to find a mapping between
    // the authenticated credentials and the client registration id
    }
    Response response = accessTokenService.form(form);
    Map<String, String> map = null;
    try {
        map = new OAuthJSONProvider().readJSONResponse((InputStream) response.getEntity());
    } catch (IOException ex) {
        throw new ResponseProcessingException(response, ex);
    }
    if (200 == response.getStatus()) {
        ClientAccessToken token = fromMapToClientToken(map, defaultTokenType);
        if (token == null) {
            throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
        }
        return token;
    } else if (response.getStatus() >= 400 && map.containsKey(OAuthConstants.ERROR_KEY)) {
        OAuthError error = new OAuthError(map.get(OAuthConstants.ERROR_KEY), map.get(OAuthConstants.ERROR_DESCRIPTION_KEY));
        error.setErrorUri(map.get(OAuthConstants.ERROR_URI_KEY));
        throw new OAuthServiceException(error);
    }
    throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
}
Also used : OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) Form(javax.ws.rs.core.Form) InputStream(java.io.InputStream) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) IOException(java.io.IOException) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) IOException(java.io.IOException) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) Response(javax.ws.rs.core.Response) OAuthError(org.apache.cxf.rs.security.oauth2.common.OAuthError) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) Map(java.util.Map) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException)

Example 3 with Consumer

use of org.apache.cxf.rs.security.oauth2.client.Consumer in project cxf by apache.

the class OAuthInvoker method performInvocation.

@Override
protected Object performInvocation(Exchange exchange, final Object serviceObject, Method m, Object[] paramArray) throws Exception {
    Message inMessage = exchange.getInMessage();
    ClientTokenContext tokenContext = inMessage.getContent(ClientTokenContext.class);
    try {
        if (tokenContext != null) {
            StaticClientTokenContext.setClientTokenContext(tokenContext);
        }
        return super.performInvocation(exchange, serviceObject, m, paramArray);
    } catch (InvocationTargetException ex) {
        if (tokenContext != null && ex.getCause() instanceof NotAuthorizedException && !inMessage.containsKey(OAUTH2_CALL_RETRIED)) {
            ClientAccessToken accessToken = tokenContext.getToken();
            String refreshToken = accessToken.getRefreshToken();
            if (refreshToken != null) {
                accessToken = OAuthClientUtils.refreshAccessToken(accessTokenServiceClient, consumer, accessToken);
                validateRefreshedToken(tokenContext, accessToken);
                MessageContext mc = new MessageContextImpl(inMessage);
                ((ClientTokenContextImpl) tokenContext).setToken(accessToken);
                clientTokenContextManager.setClientTokenContext(mc, tokenContext);
                // retry
                inMessage.put(OAUTH2_CALL_RETRIED, true);
                return super.performInvocation(exchange, serviceObject, m, paramArray);
            }
        }
        throw ex;
    } finally {
        if (tokenContext != null) {
            StaticClientTokenContext.removeClientTokenContext();
        }
    }
}
Also used : Message(org.apache.cxf.message.Message) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) InvocationTargetException(java.lang.reflect.InvocationTargetException) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Example 4 with Consumer

use of org.apache.cxf.rs.security.oauth2.client.Consumer in project cxf by apache.

the class OAuth2FiltersTest method testServiceWithTokenAndIncorrectScopeVerb.

@org.junit.Test
public void testServiceWithTokenAndIncorrectScopeVerb() throws Exception {
    URL busFile = OAuth2FiltersTest.class.getResource("client.xml");
    // Get Authorization Code
    String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
    WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(oauthClient).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    String code = OAuth2TestUtils.getAuthorizationCode(oauthClient, "read_book");
    assertNotNull(code);
    // Now get the access token
    oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(oauthClient).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code);
    assertNotNull(accessToken.getTokenKey());
    // Now invoke on the service with the access token
    String address = "https://localhost:" + PORT + "/secured/bookstore/books";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), busFile.toString());
    client.header("Authorization", "Bearer " + accessToken.getTokenKey());
    // We don't have the scope to post a book here
    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
Also used : Response(javax.ws.rs.core.Response) Book(org.apache.cxf.systest.jaxrs.security.Book) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL)

Example 5 with Consumer

use of org.apache.cxf.rs.security.oauth2.client.Consumer in project cxf by apache.

the class OAuth2FiltersTest method testServiceWithTokenUsingAudience.

@org.junit.Test
public void testServiceWithTokenUsingAudience() throws Exception {
    URL busFile = OAuth2FiltersTest.class.getResource("client.xml");
    // Get Authorization Code
    String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
    WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(oauthClient).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    String code = OAuth2TestUtils.getAuthorizationCode(oauthClient, null, "consumer-id-aud");
    assertNotNull(code);
    // Now get the access token
    oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "consumer-id-aud", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(oauthClient).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    String address = "https://localhost:" + PORT + "/secured/bookstore/books";
    ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code, "consumer-id-aud", address);
    assertNotNull(accessToken.getTokenKey());
    // Now invoke on the service with the access token
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), busFile.toString());
    client.header("Authorization", "Bearer " + accessToken.getTokenKey());
    Response response = client.type("application/xml").post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);
    Book returnedBook = response.readEntity(Book.class);
    assertEquals(returnedBook.getName(), "book");
    assertEquals(returnedBook.getId(), 123L);
}
Also used : Response(javax.ws.rs.core.Response) Book(org.apache.cxf.systest.jaxrs.security.Book) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL)

Aggregations

WebClient (org.apache.cxf.jaxrs.client.WebClient)56 ClientAccessToken (org.apache.cxf.rs.security.oauth2.common.ClientAccessToken)51 URL (java.net.URL)45 Response (javax.ws.rs.core.Response)34 Form (javax.ws.rs.core.Form)22 JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)12 Consumer (org.apache.cxf.rs.security.oauth2.client.Consumer)10 Book (org.apache.cxf.systest.jaxrs.security.Book)9 Test (org.junit.Test)8 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)7 OAuthAuthorizationData (org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)5 TokenIntrospection (org.apache.cxf.rs.security.oauth2.common.TokenIntrospection)5 ResponseProcessingException (javax.ws.rs.client.ResponseProcessingException)4 OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)4 JwtClaims (org.apache.cxf.rs.security.jose.jwt.JwtClaims)3 KeyStore (java.security.KeyStore)2 OAuthJSONProvider (org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider)2 UserInfo (org.apache.cxf.rs.security.oidc.common.UserInfo)2 AuthorizationCodeParameters (org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuth2TestUtils.AuthorizationCodeParameters)2 IOException (java.io.IOException)1