use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class AbstractAuthorizationGrantHandler method updateCacheIfEnabled.
private void updateCacheIfEnabled(AccessTokenDO newTokenBean, String scope, OauthTokenIssuer oauthTokenIssuer) throws IdentityOAuth2Exception {
if (isHashDisabled && cacheEnabled) {
AccessTokenDO tokenToCache = AccessTokenDO.clone(newTokenBean);
// method is set as the token.
if (oauthTokenIssuer.usePersistedAccessTokenAlias()) {
try {
String persistedTokenIdentifier = oauthTokenIssuer.getAccessTokenHash(newTokenBean.getAccessToken());
tokenToCache.setAccessToken(persistedTokenIdentifier);
} catch (OAuthSystemException e) {
if (log.isDebugEnabled()) {
if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
log.debug("Token issuer: " + oauthTokenIssuer.getClass() + " was tried and" + " failed to parse the received token: " + tokenToCache.getAccessToken(), e);
} else {
log.debug("Token issuer: " + oauthTokenIssuer.getClass() + " was tried and" + " failed to parse the received token.", e);
}
}
}
}
String userId;
try {
userId = tokenToCache.getAuthzUser().getUserId();
} catch (UserIdNotFoundException e) {
throw new IdentityOAuth2Exception("User id is not available for user: " + tokenToCache.getAuthzUser().getLoggableUserId(), e);
}
String authenticatedIDP = OAuth2Util.getAuthenticatedIDP(tokenToCache.getAuthzUser());
OAuthCacheKey cacheKey = getOAuthCacheKey(scope, tokenToCache.getConsumerKey(), userId, authenticatedIDP, getTokenBindingReference(tokenToCache));
oauthCache.addToCache(cacheKey, tokenToCache);
if (log.isDebugEnabled()) {
log.debug("Access token was added to OAuthCache with cache key : " + cacheKey.getCacheKeyString());
}
// Adding AccessTokenDO to improve validation performance
OAuth2Util.addTokenDOtoCache(newTokenBean);
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class TokenBindingExpiryEventHandler method handleEvent.
@Override
public void handleEvent(Event event) throws IdentityEventException {
if (log.isDebugEnabled()) {
log.debug(event.getEventName() + " event received to TokenBindingExpiryEventHandler.");
}
if (!IdentityEventConstants.EventName.SESSION_TERMINATE.name().equals(event.getEventName()) && !IdentityEventConstants.EventName.SESSION_EXPIRE.name().equals(event.getEventName())) {
return;
}
HttpServletRequest request = getHttpRequestFromEvent(event);
Map<String, Object> eventProperties = event.getEventProperties();
AuthenticationContext context = (AuthenticationContext) eventProperties.get(IdentityEventConstants.EventProperty.CONTEXT);
try {
if (request == null) {
if (log.isDebugEnabled()) {
log.debug("HttpServletRequest object is null. Hence getting the session related information from " + "event and revoking the access tokens mapped to session");
}
revokeAccessTokensMappedForSessions(event);
return;
}
if (FrameworkConstants.RequestType.CLAIM_TYPE_OIDC.equals(request.getParameter(TYPE))) {
String consumerKey = context.getRelyingParty();
String bindingType = null;
if (StringUtils.isNotBlank(consumerKey)) {
bindingType = OAuth2Util.getAppInformationByClientId(consumerKey).getTokenBindingType();
}
if (bindingType != null) {
revokeTokensForBindingType(request, context.getLastAuthenticatedUser(), consumerKey, bindingType);
}
if (!OAuth2Constants.TokenBinderType.SSO_SESSION_BASED_TOKEN_BINDER.equals(bindingType)) {
revokeTokensForCommonAuthCookie(request, context.getLastAuthenticatedUser());
}
} else {
revokeTokensForCommonAuthCookie(request, context.getLastAuthenticatedUser());
}
} catch (IdentityOAuth2Exception | OAuthSystemException e) {
log.error("Error while revoking the tokens on session termination.", e);
} catch (InvalidOAuthClientException e) {
if (log.isDebugEnabled()) {
log.debug("Error while revoking the tokens on session termination.", e);
}
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project gobblin by apache.
the class SalesforceRestWriter method onConnect.
/**
* Retrieve access token, if needed, retrieve instance url, and set server host URL
* {@inheritDoc}
* @see org.apache.gobblin.writer.http.HttpWriter#onConnect(org.apache.http.HttpHost)
*/
@Override
public void onConnect(URI serverHost) throws IOException {
if (!StringUtils.isEmpty(accessToken)) {
// No need to be called if accessToken is active.
return;
}
try {
getLog().info("Getting Oauth2 access token.");
OAuthClientRequest request = OAuthClientRequest.tokenLocation(serverHost.toString()).setGrantType(GrantType.PASSWORD).setClientId(clientId).setClientSecret(clientSecret).setUsername(userId).setPassword(password + securityToken).buildQueryMessage();
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse response = client.accessToken(request, OAuth.HttpMethod.POST);
accessToken = response.getAccessToken();
setCurServerHost(new URI(response.getParam("instance_url")));
} catch (OAuthProblemException e) {
throw new NonTransientException("Error while authenticating with Oauth2", e);
} catch (OAuthSystemException e) {
throw new RuntimeException("Failed getting access token", e);
} catch (URISyntaxException e) {
throw new RuntimeException("Failed due to invalid instance url", e);
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project fattureincloud-java-sdk by fattureincloud.
the class OAuthOkHttpClient method execute.
@Override
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
MediaType mediaType = MediaType.parse("application/json");
Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
if (entry.getKey().equalsIgnoreCase("Content-Type")) {
mediaType = MediaType.parse(entry.getValue());
} else {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
}
RequestBody body = request.getBody() != null ? RequestBody.create(request.getBody(), mediaType) : null;
requestBuilder.method(requestMethod, body);
try {
Response response = client.newCall(requestBuilder.build()).execute();
return OAuthClientResponseFactory.createCustomResponse(response.body().string(), response.body().contentType().toString(), response.code(), responseClass);
} catch (IOException e) {
throw new OAuthSystemException(e);
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project fattureincloud-java-sdk by fattureincloud.
the class RetryingOAuth method retryingIntercept.
private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException {
Request request = chain.request();
// If the request already has an authorization (e.g. Basic auth), proceed with the request as is
if (request.header("Authorization") != null) {
return chain.proceed(request);
}
// Get the token if it has not yet been acquired
if (getAccessToken() == null) {
updateAccessToken(null);
}
OAuthClientRequest oAuthRequest;
if (getAccessToken() != null) {
// Build the request
Request.Builder requestBuilder = request.newBuilder();
String requestAccessToken = getAccessToken();
try {
oAuthRequest = new OAuthBearerClientRequest(request.url().toString()).setAccessToken(requestAccessToken).buildHeaderMessage();
} catch (OAuthSystemException e) {
throw new IOException(e);
}
Map<String, String> headers = oAuthRequest.getHeaders();
for (String headerName : headers.keySet()) {
requestBuilder.addHeader(headerName, headers.get(headerName));
}
requestBuilder.url(oAuthRequest.getLocationUri());
// Execute the request
Response response = chain.proceed(requestBuilder.build());
// 401/403 response codes most likely indicate an expired access token, unless it happens two times in a row
if (response != null && (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED || response.code() == HttpURLConnection.HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) {
try {
if (updateAccessToken(requestAccessToken)) {
response.body().close();
return retryingIntercept(chain, false);
}
} catch (Exception e) {
response.body().close();
throw e;
}
}
return response;
} else {
return chain.proceed(chain.request());
}
}
Aggregations