Search in sources :

Example 91 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method authorize.

@GET
@Path("/")
@Consumes("application/x-www-form-urlencoded")
@Produces("text/html")
public Response authorize(@Context HttpServletRequest request, @Context HttpServletResponse response) throws URISyntaxException, InvalidRequestParentException {
    OAuthMessage oAuthMessage;
    // TODO: 2021-01-22 Check for the flag in request.
    setCommonAuthIdToRequest(request, response);
    // Using a separate try-catch block as this next try block has operations in the final block.
    try {
        oAuthMessage = buildOAuthMessage(request, response);
    } catch (InvalidRequestParentException e) {
        EndpointUtil.triggerOnAuthzRequestException(e, request);
        throw e;
    }
    try {
        // Start tenant domain flow if the tenant configuration is not enabled.
        if (!IdentityTenantUtil.isTenantedSessionsEnabled()) {
            String tenantDomain = EndpointUtil.getSPTenantDomainFromClientId(oAuthMessage.getClientId());
            FrameworkUtils.startTenantFlow(tenantDomain);
        }
        if (isPassthroughToFramework(oAuthMessage)) {
            return handleAuthFlowThroughFramework(oAuthMessage);
        } else if (isInitialRequestFromClient(oAuthMessage)) {
            return handleInitialAuthorizationRequest(oAuthMessage);
        } else if (isAuthenticationResponseFromFramework(oAuthMessage)) {
            return handleAuthenticationResponse(oAuthMessage);
        } else if (isConsentResponseFromUser(oAuthMessage)) {
            return handleResponseFromConsent(oAuthMessage);
        } else {
            return handleInvalidRequest(oAuthMessage);
        }
    } catch (OAuthProblemException e) {
        EndpointUtil.triggerOnAuthzRequestException(e, request);
        return handleOAuthProblemException(oAuthMessage, e);
    } catch (OAuthSystemException e) {
        EndpointUtil.triggerOnAuthzRequestException(e, request);
        return handleOAuthSystemException(oAuthMessage, e);
    } finally {
        handleCachePersistence(oAuthMessage);
        if (!IdentityTenantUtil.isTenantedSessionsEnabled()) {
            FrameworkUtils.endTenantFlow();
        }
    }
}
Also used : InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthMessage(org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 92 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class JWTTokenIssuer method getAccessTokenHash.

@Override
public String getAccessTokenHash(String accessToken) throws OAuthSystemException {
    try {
        JWT parsedJwtToken = JWTParser.parse(accessToken);
        String jwtId = parsedJwtToken.getJWTClaimsSet().getJWTID();
        if (jwtId == null) {
            throw new OAuthSystemException("JTI could not be retrieved from the JWT token.");
        }
        return jwtId;
    } catch (ParseException e) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            log.debug("Error while getting JWTID from token: " + accessToken);
        }
        throw new OAuthSystemException("Error while getting access token hash", e);
    }
}
Also used : PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) ParseException(java.text.ParseException)

Example 93 with OAuthSystemException

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);
    }
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 94 with OAuthSystemException

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);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 95 with OAuthSystemException

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);
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) NonTransientException(org.apache.gobblin.exception.NonTransientException) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) URISyntaxException(java.net.URISyntaxException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)100 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)47 IOException (java.io.IOException)37 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)36 Request (okhttp3.Request)27 Response (okhttp3.Response)27 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)20 Builder (okhttp3.Request.Builder)17 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)17 Map (java.util.Map)15 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)15 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)14 MediaType (okhttp3.MediaType)13 RequestBody (okhttp3.RequestBody)13 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)12 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)11 Path (javax.ws.rs.Path)10 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)9 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)9 HashMap (java.util.HashMap)8