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();
}
}
}
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);
}
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();
}
}
}
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);
}
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);
}
Aggregations