Search in sources :

Example 16 with OAuthRevocationResponseDTO

use of org.wso2.carbon.identity.oauth.dto.OAuthRevocationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2Service method buildErrorResponse.

private OAuthRevocationResponseDTO buildErrorResponse(String errorCode, String errorMessage) {
    OAuthRevocationResponseDTO revokeRespDTO = new OAuthRevocationResponseDTO();
    revokeRespDTO.setError(true);
    revokeRespDTO.setErrorCode(errorCode);
    revokeRespDTO.setErrorMsg(errorMessage);
    return revokeRespDTO;
}
Also used : OAuthRevocationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuthRevocationResponseDTO)

Example 17 with OAuthRevocationResponseDTO

use of org.wso2.carbon.identity.oauth.dto.OAuthRevocationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2Service method revokeTokenByOAuthClient.

/**
 * Revoke tokens issued to OAuth clients
 *
 * @param revokeRequestDTO DTO representing consumerKey, consumerSecret and tokens[]
 * @return revokeRespDTO DTO representing success or failure message
 */
public OAuthRevocationResponseDTO revokeTokenByOAuthClient(OAuthRevocationRequestDTO revokeRequestDTO) {
    // fix here remove associated cache entry
    OAuthRevocationResponseDTO revokeResponseDTO = new OAuthRevocationResponseDTO();
    OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance().getOAuthEventInterceptorProxy();
    OAuthClientAuthnContext oAuthClientAuthnContext = revokeRequestDTO.getoAuthClientAuthnContext();
    if (!isClientAuthenticated(oAuthClientAuthnContext)) {
        try {
            // Returns the authentication failure error if the client doesn't support implicit grant
            if (!isImplicitGrantSupportedClient(revokeRequestDTO.getConsumerKey())) {
                return buildErrorResponse(getErrorCode(oAuthClientAuthnContext), getErrorMessage(oAuthClientAuthnContext));
            }
        } catch (IdentityOAuth2Exception e) {
            log.error("Error occurred while checking client authentication.", e);
            return buildErrorResponse(OAuth2ErrorCodes.SERVER_ERROR, "Error occurred while revoking " + "authorization grant for application.");
        } catch (InvalidOAuthClientException e) {
            if (log.isDebugEnabled()) {
                log.debug("Client Authentication failed.", e);
            }
            return buildErrorResponse(OAuth2ErrorCodes.INVALID_CLIENT, "Client Authentication failed.");
        }
    }
    if (oAuthEventInterceptorProxy != null && oAuthEventInterceptorProxy.isEnabled()) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            oAuthEventInterceptorProxy.onPreTokenRevocationByClient(revokeRequestDTO, paramMap);
        } catch (IdentityOAuth2Exception e) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "revoke-token", null);
            log.error(e);
            revokeResponseDTO.setError(true);
            revokeResponseDTO.setErrorCode(OAuth2ErrorCodes.SERVER_ERROR);
            revokeResponseDTO.setErrorMsg("Error occurred while revoking authorization grant for applications");
            return revokeResponseDTO;
        }
    }
    RefreshTokenValidationDataDO refreshTokenDO = null;
    AccessTokenDO accessTokenDO = null;
    try {
        if (StringUtils.isNotEmpty(revokeRequestDTO.getConsumerKey()) && StringUtils.isNotEmpty(revokeRequestDTO.getToken())) {
            boolean refreshTokenFirst = false;
            if (isRefreshTokenType(revokeRequestDTO)) {
                refreshTokenFirst = true;
            }
            if (refreshTokenFirst) {
                refreshTokenDO = OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().validateRefreshToken(revokeRequestDTO.getConsumerKey(), revokeRequestDTO.getToken());
                if (refreshTokenDO == null || StringUtils.isEmpty(refreshTokenDO.getRefreshTokenState()) || !(OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(refreshTokenDO.getRefreshTokenState()) || OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED.equals(refreshTokenDO.getRefreshTokenState()))) {
                    accessTokenDO = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessToken(revokeRequestDTO.getToken(), true);
                    refreshTokenDO = null;
                }
            } else {
                accessTokenDO = OAuth2Util.findAccessToken(revokeRequestDTO.getToken(), true);
                if (accessTokenDO == null) {
                    refreshTokenDO = OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().validateRefreshToken(revokeRequestDTO.getConsumerKey(), revokeRequestDTO.getToken());
                    if (refreshTokenDO == null || StringUtils.isEmpty(refreshTokenDO.getRefreshTokenState()) || !(OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(refreshTokenDO.getRefreshTokenState()) || OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED.equals(refreshTokenDO.getRefreshTokenState()))) {
                        Map<String, Object> params = new HashMap<>();
                        params.put("clientId", revokeRequestDTO.getConsumerKey());
                        if (LoggerUtils.isDiagnosticLogsEnabled()) {
                            if (refreshTokenDO == null || StringUtils.isEmpty(refreshTokenDO.getRefreshTokenState())) {
                                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Invalid token.", "revoke-token", null);
                            } else if (OAuthConstants.TokenStates.TOKEN_STATE_REVOKED.equals(refreshTokenDO.getRefreshTokenState())) {
                                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Provided token is already revoked.", "revoke-token", null);
                            } else if (OAuthConstants.TokenStates.TOKEN_STATE_INACTIVE.equals(refreshTokenDO.getRefreshTokenState())) {
                                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Provided token is in inactive state.", "revoke-token", null);
                            }
                        }
                        refreshTokenDO = null;
                    }
                }
            }
            String grantType = StringUtils.EMPTY;
            if (accessTokenDO != null) {
                grantType = accessTokenDO.getGrantType();
            } else if (refreshTokenDO != null) {
                grantType = refreshTokenDO.getGrantType();
            }
            if (!isClientAuthenticated(oAuthClientAuthnContext, grantType)) {
                if (LoggerUtils.isDiagnosticLogsEnabled()) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("clientId", revokeRequestDTO.getConsumerKey());
                    LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "OAuth client authentication is unsuccessful.", "revoke-token", null);
                }
                OAuthRevocationResponseDTO revokeRespDTO = new OAuthRevocationResponseDTO();
                revokeRespDTO.setError(true);
                revokeRespDTO.setErrorCode(getErrorCode(oAuthClientAuthnContext));
                revokeRespDTO.setErrorMsg(getErrorMessage(oAuthClientAuthnContext));
                invokePostRevocationListeners(revokeRequestDTO, revokeRespDTO, accessTokenDO, refreshTokenDO);
                return revokeRespDTO;
            }
            if (refreshTokenDO != null) {
                String tokenBindingReference = NONE;
                if (StringUtils.isNotBlank(refreshTokenDO.getTokenBindingReference())) {
                    tokenBindingReference = refreshTokenDO.getTokenBindingReference();
                }
                OAuthUtil.clearOAuthCache(revokeRequestDTO.getConsumerKey(), refreshTokenDO.getAuthorizedUser(), OAuth2Util.buildScopeString(refreshTokenDO.getScope()), tokenBindingReference);
                OAuthUtil.clearOAuthCache(revokeRequestDTO.getConsumerKey(), refreshTokenDO.getAuthorizedUser(), OAuth2Util.buildScopeString(refreshTokenDO.getScope()));
                OAuthUtil.clearOAuthCache(revokeRequestDTO.getConsumerKey(), refreshTokenDO.getAuthorizedUser());
                OAuthUtil.clearOAuthCache(refreshTokenDO.getAccessToken());
                OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().revokeAccessTokens(new String[] { refreshTokenDO.getAccessToken() });
                addRevokeResponseHeaders(revokeResponseDTO, refreshTokenDO.getAccessToken(), revokeRequestDTO.getToken(), refreshTokenDO.getAuthorizedUser().toString());
            } else if (accessTokenDO != null) {
                if (revokeRequestDTO.getConsumerKey().equals(accessTokenDO.getConsumerKey())) {
                    if ((OAuth2Util.getAppInformationByClientId(accessTokenDO.getConsumerKey()).isTokenBindingValidationEnabled()) && (!isValidTokenBinding(accessTokenDO.getTokenBinding(), revokeRequestDTO.getRequest()))) {
                        if (LoggerUtils.isDiagnosticLogsEnabled()) {
                            Map<String, Object> params = new HashMap<>();
                            params.put("clientId", accessTokenDO.getConsumerKey());
                            if (accessTokenDO.getTokenBinding() != null) {
                                params.put("tokenBindingType", accessTokenDO.getTokenBinding().getBindingType());
                                params.put("tokenBindingValue", accessTokenDO.getTokenBinding().getBindingValue());
                            }
                            Map<String, Object> configs = new HashMap<>();
                            configs.put("isTokenBindingValidationEnabled", "true");
                            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Valid token binding value not present in the request.", "validate-token-binding", configs);
                        }
                        revokeResponseDTO.setError(true);
                        revokeResponseDTO.setErrorCode(OAuth2ErrorCodes.ACCESS_DENIED);
                        revokeResponseDTO.setErrorMsg("Valid token binding value not present in the request.");
                        return revokeResponseDTO;
                    }
                    String tokenBindingReference = NONE;
                    if (accessTokenDO.getTokenBinding() != null && StringUtils.isNotBlank(accessTokenDO.getTokenBinding().getBindingReference())) {
                        tokenBindingReference = accessTokenDO.getTokenBinding().getBindingReference();
                    }
                    OAuthUtil.clearOAuthCache(revokeRequestDTO.getConsumerKey(), accessTokenDO.getAuthzUser(), OAuth2Util.buildScopeString(accessTokenDO.getScope()), tokenBindingReference);
                    OAuthUtil.clearOAuthCache(revokeRequestDTO.getConsumerKey(), accessTokenDO.getAuthzUser(), OAuth2Util.buildScopeString(accessTokenDO.getScope()));
                    OAuthUtil.clearOAuthCache(revokeRequestDTO.getConsumerKey(), accessTokenDO.getAuthzUser());
                    OAuthUtil.clearOAuthCache(accessTokenDO);
                    String scope = OAuth2Util.buildScopeString(accessTokenDO.getScope());
                    String userId = accessTokenDO.getAuthzUser().getUserId();
                    synchronized ((revokeRequestDTO.getConsumerKey() + ":" + userId + ":" + scope + ":" + tokenBindingReference).intern()) {
                        OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().revokeAccessTokens(new String[] { accessTokenDO.getAccessToken() });
                    }
                    addRevokeResponseHeaders(revokeResponseDTO, revokeRequestDTO.getToken(), accessTokenDO.getRefreshToken(), accessTokenDO.getAuthzUser().toString());
                } else {
                    if (LoggerUtils.isDiagnosticLogsEnabled()) {
                        Map<String, Object> params = new HashMap<>();
                        params.put("clientId", accessTokenDO.getConsumerKey());
                        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Client is not authorized.", "validate-oauth-client", null);
                    }
                    throw new InvalidOAuthClientException("Unauthorized Client");
                }
            }
            invokePostRevocationListeners(revokeRequestDTO, revokeResponseDTO, accessTokenDO, refreshTokenDO);
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                if (accessTokenDO != null) {
                    params.put("clientId", accessTokenDO.getConsumerKey());
                }
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Token revocation is successful.", "revoke-tokens", null);
            }
            return revokeResponseDTO;
        } else {
            Map<String, Object> params = new HashMap<>();
            if (StringUtils.isNotBlank(revokeRequestDTO.getConsumerKey())) {
                params.put("clientId", revokeRequestDTO.getConsumerKey());
            } else {
                if (LoggerUtils.isDiagnosticLogsEnabled()) {
                    LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "'client_id' is empty in request.", "validate-input-parameters", null);
                }
            }
            if (StringUtils.isBlank(revokeRequestDTO.getToken())) {
                if (LoggerUtils.isDiagnosticLogsEnabled()) {
                    LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "'token' is empty in request.", "validate-input-parameters", null);
                }
            }
            revokeResponseDTO.setError(true);
            revokeResponseDTO.setErrorCode(oAuthClientAuthnContext.getErrorCode());
            revokeResponseDTO.setErrorMsg(oAuthClientAuthnContext.getErrorMessage());
            invokePostRevocationListeners(revokeRequestDTO, revokeResponseDTO, accessTokenDO, refreshTokenDO);
            return revokeResponseDTO;
        }
    } catch (InvalidOAuthClientException e) {
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "Client is not authorized.", "validate-oauth-client", null);
        if (log.isDebugEnabled()) {
            log.debug("Unauthorized client.", e);
        }
        OAuthRevocationResponseDTO revokeRespDTO = new OAuthRevocationResponseDTO();
        revokeRespDTO.setError(true);
        revokeRespDTO.setErrorCode(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
        revokeRespDTO.setErrorMsg("Unauthorized Client");
        invokePostRevocationListeners(revokeRequestDTO, revokeResponseDTO, accessTokenDO, refreshTokenDO);
        return revokeRespDTO;
    } catch (IdentityException e) {
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "revoke-tokens", null);
        log.error("Error occurred while revoking authorization grant for applications", e);
        OAuthRevocationResponseDTO revokeRespDTO = new OAuthRevocationResponseDTO();
        revokeRespDTO.setError(true);
        revokeRespDTO.setErrorCode(OAuth2ErrorCodes.SERVER_ERROR);
        revokeRespDTO.setErrorMsg("Error occurred while revoking authorization grant for applications");
        invokePostRevocationListeners(revokeRequestDTO, revokeResponseDTO, accessTokenDO, refreshTokenDO);
        return revokeRespDTO;
    }
}
Also used : HashMap(java.util.HashMap) OAuthRevocationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuthRevocationResponseDTO) IdentityException(org.wso2.carbon.identity.base.IdentityException) OAuthClientAuthnContext(org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) RefreshTokenValidationDataDO(org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO) OAuthEventInterceptor(org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor) Map(java.util.Map) HashMap(java.util.HashMap) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 18 with OAuthRevocationResponseDTO

use of org.wso2.carbon.identity.oauth.dto.OAuthRevocationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuthRevocationEndpoint method handleRevokeResponse.

private Response handleRevokeResponse(String callback, OAuthRevocationResponseDTO oauthRevokeResp) throws OAuthSystemException {
    OAuthResponse response;
    if (isNotEmpty(callback)) {
        response = CarbonOAuthASResponse.revokeResponse(HttpServletResponse.SC_OK).buildBodyMessage();
        response.setBody(callback + "();");
    } else {
        response = CarbonOAuthASResponse.revokeResponse(HttpServletResponse.SC_OK).buildBodyMessage();
    }
    ResponseHeader[] headers = oauthRevokeResp.getResponseHeaders();
    ResponseBuilder respBuilder = Response.status(response.getResponseStatus()).header(HTTP_RESP_HEADER_CACHE_CONTROL, HTTP_RESP_HEADER_VAL_CACHE_CONTROL_NO_STORE).header(HTTPConstants.HEADER_CONTENT_LENGTH, "0").header(HTTP_RESP_HEADER_PRAGMA, HTTP_RESP_HEADER_VAL_PRAGMA_NO_CACHE);
    if (headers != null) {
        for (ResponseHeader header : headers) {
            if (header != null) {
                respBuilder.header(header.getKey(), header.getValue());
            }
        }
    }
    if (isNotEmpty(callback)) {
        respBuilder.header(HttpHeaders.CONTENT_TYPE, APPLICATION_JAVASCRIPT);
    } else {
        respBuilder.header(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
    }
    return respBuilder.entity(response.getBody()).build();
}
Also used : ResponseHeader(org.wso2.carbon.identity.oauth2.ResponseHeader) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse)

Example 19 with OAuthRevocationResponseDTO

use of org.wso2.carbon.identity.oauth.dto.OAuthRevocationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuthAdminServiceImpl method revokeIssuedTokensByApplication.

/**
 * Revoke issued tokens for the application.
 *
 * @param application {@link OAuthAppRevocationRequestDTO}
 * @return revokeRespDTO {@link OAuthAppRevocationRequestDTO}
 * @throws IdentityOAuthAdminException Error while revoking the issued tokens
 */
public OAuthRevocationResponseDTO revokeIssuedTokensByApplication(OAuthAppRevocationRequestDTO application) throws IdentityOAuthAdminException {
    triggerPreApplicationTokenRevokeListeners(application);
    OAuthRevocationResponseDTO revokeRespDTO = new OAuthRevocationResponseDTO();
    String consumerKey = application.getConsumerKey();
    if (StringUtils.isBlank(consumerKey)) {
        revokeRespDTO.setError(true);
        revokeRespDTO.setErrorCode(OAuth2ErrorCodes.INVALID_REQUEST);
        revokeRespDTO.setErrorMsg("Consumer key is null or empty.");
        triggerPostApplicationTokenRevokeListeners(application, revokeRespDTO, new ArrayList<>());
        return revokeRespDTO;
    }
    String tenantDomain = getTenantDomain(consumerKey);
    String applicationName = getApplicationName(consumerKey, tenantDomain);
    List<AccessTokenDO> accessTokenDOs = getActiveAccessTokensByConsumerKey(consumerKey);
    if (accessTokenDOs.size() > 0) {
        String[] accessTokens = new String[accessTokenDOs.size()];
        int count = 0;
        for (AccessTokenDO accessTokenDO : accessTokenDOs) {
            accessTokens[count++] = accessTokenDO.getAccessToken();
            clearCacheByAccessTokenAndConsumerKey(accessTokenDO, consumerKey);
        }
        if (LOG.isDebugEnabled()) {
            String message = String.format("Access tokens and token of users are removed from the cache for " + "OAuth app in tenant domain: %s with consumer key: %s.", tenantDomain, consumerKey);
            LOG.debug(message);
        }
        revokeAccessTokens(accessTokens, consumerKey, tenantDomain);
        revokeOAuthConsentsForApplication(applicationName, tenantDomain);
    }
    triggerPostApplicationTokenRevokeListeners(application, revokeRespDTO, accessTokenDOs);
    return revokeRespDTO;
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthRevocationResponseDTO(org.wso2.carbon.identity.oauth.dto.OAuthRevocationResponseDTO) OAuth2Util.buildScopeString(org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString)

Aggregations

OAuthRevocationResponseDTO (org.wso2.carbon.identity.oauth.dto.OAuthRevocationResponseDTO)9 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)7 OAuthRevocationResponseDTO (org.wso2.carbon.identity.oauth2.dto.OAuthRevocationResponseDTO)6 HashMap (java.util.HashMap)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 Test (org.testng.annotations.Test)5 OAuthRevocationRequestDTO (org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO)5 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)5 IdentityOAuthAdminException (org.wso2.carbon.identity.oauth.IdentityOAuthAdminException)4 OAuthRevocationRequestDTO (org.wso2.carbon.identity.oauth.dto.OAuthRevocationRequestDTO)4 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)4 OAuth2Util.buildScopeString (org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString)4 OAuthAppRevocationRequestDTO (org.wso2.carbon.identity.oauth.dto.OAuthAppRevocationRequestDTO)3 OAuthConsumerAppDTO (org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)3 OAuthEventInterceptor (org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor)3 Arrays (java.util.Arrays)2 List (java.util.List)2 Optional (java.util.Optional)2 Collectors (java.util.stream.Collectors)2 Response (javax.ws.rs.core.Response)2