Search in sources :

Example 1 with OAuthRevocationRequestDTO

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

the class OAuthRevocationEndpointTest method testRevokeAccessToken.

@Test(dataProvider = "testRevokeAccessTokenDataProvider")
public void testRevokeAccessToken(String authzHeader, boolean addReqParams, String token, String tokenHint, String callback, String clientId, String secret, String respError, Object headerObj, Exception e, int expectedStatus, String expectedErrorCode) throws Exception {
    MultivaluedMap<String, String> parameterMap = new MultivaluedHashMap<String, String>();
    ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj;
    parameterMap.add(TOKEN_PARAM, token);
    parameterMap.add(TOKEN_TYPE_HINT_PARAM, tokenHint);
    parameterMap.add(CALLBACK_PARAM, callback);
    Map<String, String[]> requestedParams = new HashMap<>();
    if (addReqParams) {
        requestedParams.put(TOKEN_PARAM, new String[] { "" });
        requestedParams.put(TOKEN_TYPE_HINT_PARAM, new String[] { "" });
        requestedParams.put(CALLBACK_PARAM, new String[] { "" });
    }
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
    HttpServletRequest request = mockHttpRequest(requestedParams, new HashMap<String, Object>());
    when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(authzHeader);
    spy(EndpointUtil.class);
    doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
    final OAuthRevocationRequestDTO[] revokeReqDTO;
    revokeReqDTO = new OAuthRevocationRequestDTO[1];
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            revokeReqDTO[0] = (OAuthRevocationRequestDTO) invocation.getArguments()[0];
            return oAuthRevocationResponseDTO;
        }
    }).when(oAuth2Service).revokeTokenByOAuthClient(any(OAuthRevocationRequestDTO.class));
    when(oAuthRevocationResponseDTO.getErrorCode()).thenReturn(respError);
    when(oAuthRevocationResponseDTO.getErrorMsg()).thenReturn(respError);
    when(oAuthRevocationResponseDTO.getResponseHeaders()).thenReturn(responseHeaders);
    Response response;
    try {
        response = revocationEndpoint.revokeAccessToken(request, parameterMap);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Token response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
    assertNotNull(response.getEntity(), "Response entity is null");
    if (expectedErrorCode != null) {
        assertTrue(response.getEntity().toString().contains(expectedErrorCode), "Expected error code not found");
        if (StringUtils.isNotEmpty(callback)) {
            assertTrue(response.getEntity().toString().contains(callback), "Callback is not added to the response");
        }
    }
}
Also used : OAuthRevocationRequestDTO(org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO) ResponseHeader(org.wso2.carbon.identity.oauth2.ResponseHeader) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Matchers.anyString(org.mockito.Matchers.anyString) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 2 with OAuthRevocationRequestDTO

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

the class ResponseTypeHandlerUtil method revokeExistingToken.

/**
 * Builds the revocation request and calls the revoke oauth service.
 *
 * @param clientId client id.
 * @param accessToken access token.
 */
private static void revokeExistingToken(String clientId, String accessToken) throws IdentityOAuth2Exception {
    // This is used to avoid client validation failure in revokeTokenByOAuthClient.
    // This will not affect the flow negatively as the client is already authenticated by this point.
    OAuthClientAuthnContext oAuthClientAuthnContext = buildAuthenticatedOAuthClientAuthnContext(clientId);
    OAuthRevocationRequestDTO revocationRequestDTO = OAuth2Util.buildOAuthRevocationRequest(oAuthClientAuthnContext, accessToken);
    OAuthRevocationResponseDTO revocationResponseDTO = getOauth2Service().revokeTokenByOAuthClient(revocationRequestDTO);
    if (revocationResponseDTO.isError()) {
        String msg = "Error while revoking tokens for clientId:" + clientId + " Error Message:" + revocationResponseDTO.getErrorMsg();
        if (revocationResponseDTO.getErrorCode().equals(OAuth2ErrorCodes.SERVER_ERROR)) {
            log.error(msg);
        }
        if (log.isDebugEnabled()) {
            log.debug(msg);
        }
        throw new IdentityOAuth2Exception(msg);
    }
}
Also used : OAuthRevocationRequestDTO(org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthRevocationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuthRevocationResponseDTO) OAuthClientAuthnContext(org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext)

Example 3 with OAuthRevocationRequestDTO

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

the class OAuth2Service method invokePostRevocationListeners.

private void invokePostRevocationListeners(OAuthRevocationRequestDTO revokeRequestDTO, OAuthRevocationResponseDTO revokeResponseDTO, AccessTokenDO accessTokenDO, RefreshTokenValidationDataDO refreshTokenDO) {
    OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance().getOAuthEventInterceptorProxy();
    if (oAuthEventInterceptorProxy != null && oAuthEventInterceptorProxy.isEnabled()) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            oAuthEventInterceptorProxy.onPostTokenRevocationByClient(revokeRequestDTO, revokeResponseDTO, accessTokenDO, refreshTokenDO, paramMap);
        } catch (IdentityOAuth2Exception e) {
            log.error("Error occurred when invoking post token revoke listener ", e);
        }
    }
}
Also used : HashMap(java.util.HashMap) OAuthEventInterceptor(org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor)

Example 4 with OAuthRevocationRequestDTO

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

the class OAuthAdminServiceImpl method triggerPostRevokeListeners.

void triggerPostRevokeListeners(OAuthRevocationRequestDTO revokeRequestDTO, OAuthRevocationResponseDTO revokeRespDTO, AccessTokenDO[] accessTokenDOs) {
    OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance().getOAuthEventInterceptorProxy();
    for (AccessTokenDO accessTokenDO : accessTokenDOs) {
        if (oAuthEventInterceptorProxy != null && oAuthEventInterceptorProxy.isEnabled()) {
            try {
                Map<String, Object> paramMap = new HashMap<String, Object>();
                oAuthEventInterceptorProxy.onPostTokenRevocationByResourceOwner(revokeRequestDTO, revokeRespDTO, accessTokenDO, paramMap);
            } catch (IdentityOAuth2Exception e) {
                LOG.error("Error occurred with post revocation listener.", e);
            }
        }
    }
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) HashMap(java.util.HashMap) OAuth2Util.buildScopeString(org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString) OAuthEventInterceptor(org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor)

Example 5 with OAuthRevocationRequestDTO

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

the class OAuthAdminServiceImpl method revokeAuthzForAppsByResourceOwner.

/**
 * Revoke authorization for OAuth apps by resource owners
 *
 * @param revokeRequestDTO DTO representing authorized user and apps[]
 * @return revokeRespDTO DTO representing success or failure message
 */
public OAuthRevocationResponseDTO revokeAuthzForAppsByResourceOwner(OAuthRevocationRequestDTO revokeRequestDTO) throws IdentityOAuthAdminException {
    triggerPreRevokeListeners(revokeRequestDTO);
    if (revokeRequestDTO.getApps() != null && revokeRequestDTO.getApps().length > 0) {
        String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        String tenantAwareLoggedInUserName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
        AuthenticatedUser user = buildAuthenticatedUser(tenantAwareLoggedInUserName, tenantDomain);
        String userName = UserCoreUtil.addTenantDomainToEntry(tenantAwareLoggedInUserName, tenantDomain);
        String userStoreDomain = null;
        if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) {
            try {
                userStoreDomain = OAuth2Util.getUserStoreForFederatedUser(user);
            } catch (IdentityOAuth2Exception e) {
                throw handleError("Error occurred while getting user store domain from User ID : " + user, e);
            }
        }
        OAuthConsumerAppDTO[] appDTOs = getAppsAuthorizedByUser();
        for (String appName : revokeRequestDTO.getApps()) {
            for (OAuthConsumerAppDTO appDTO : appDTOs) {
                if (appDTO.getApplicationName().equals(appName)) {
                    Set<AccessTokenDO> accessTokenDOs;
                    try {
                        // Retrieve all ACTIVE or EXPIRED access tokens for particular client authorized by this
                        // user
                        accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(appDTO.getOauthConsumerKey(), user, userStoreDomain, true);
                    } catch (IdentityOAuth2Exception e) {
                        String errorMsg = "Error occurred while retrieving access tokens issued for " + "Client ID : " + appDTO.getOauthConsumerKey() + ", User ID : " + userName;
                        throw handleError(errorMsg, e);
                    }
                    AuthenticatedUser authzUser;
                    for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                        // Clear cache with AccessTokenDO
                        authzUser = accessTokenDO.getAuthzUser();
                        String tokenBindingReference = NONE;
                        if (accessTokenDO.getTokenBinding() != null && StringUtils.isNotBlank(accessTokenDO.getTokenBinding().getBindingReference())) {
                            tokenBindingReference = accessTokenDO.getTokenBinding().getBindingReference();
                        }
                        OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, buildScopeString(accessTokenDO.getScope()), tokenBindingReference);
                        OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, buildScopeString(accessTokenDO.getScope()));
                        OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser);
                        OAuthUtil.clearOAuthCache(accessTokenDO);
                        AccessTokenDO scopedToken;
                        try {
                            // Retrieve latest access token for particular client, user and scope combination if
                            // its ACTIVE or EXPIRED.
                            scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(appDTO.getOauthConsumerKey(), user, userStoreDomain, buildScopeString(accessTokenDO.getScope()), true);
                        } catch (IdentityOAuth2Exception e) {
                            String errorMsg = "Error occurred while retrieving latest " + "access token issued for Client ID : " + appDTO.getOauthConsumerKey() + ", User ID : " + userName + " and Scope : " + buildScopeString(accessTokenDO.getScope());
                            throw handleError(errorMsg, e);
                        }
                        if (scopedToken != null) {
                            // Revoking token from database
                            try {
                                OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().revokeAccessTokens(new String[] { scopedToken.getAccessToken() });
                            } catch (IdentityOAuth2Exception e) {
                                String errorMsg = "Error occurred while revoking " + "Access Token : " + scopedToken.getAccessToken();
                                throw handleError(errorMsg, e);
                            }
                            // Revoking the oauth consent from database.
                            try {
                                OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().revokeOAuthConsentByApplicationAndUser(authzUser.getAuthenticatedSubjectIdentifier(), tenantDomain, appName);
                            } catch (IdentityOAuth2Exception e) {
                                String errorMsg = "Error occurred while removing OAuth Consent of Application: " + appName + " of user: " + userName;
                                throw handleError(errorMsg, e);
                            }
                        }
                        triggerPostRevokeListeners(revokeRequestDTO, new OAuthRevocationResponseDTO(), accessTokenDOs.toArray(new AccessTokenDO[0]));
                    }
                }
            }
        }
    } else {
        OAuthRevocationResponseDTO revokeRespDTO = new OAuthRevocationResponseDTO();
        revokeRespDTO.setError(true);
        revokeRespDTO.setErrorCode(OAuth2ErrorCodes.INVALID_REQUEST);
        revokeRespDTO.setErrorMsg("Invalid revocation request");
        // passing a single element array with null element to make sure listeners are triggered at least once
        triggerPostRevokeListeners(revokeRequestDTO, revokeRespDTO, new AccessTokenDO[] { null });
        return revokeRespDTO;
    }
    return new OAuthRevocationResponseDTO();
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) OAuthRevocationResponseDTO(org.wso2.carbon.identity.oauth.dto.OAuthRevocationResponseDTO) OAuth2Util.buildScopeString(org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Aggregations

OAuthRevocationRequestDTO (org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO)12 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 Test (org.testng.annotations.Test)7 OAuthClientAuthnContext (org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext)7 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)7 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)7 HashMap (java.util.HashMap)6 OAuthRevocationResponseDTO (org.wso2.carbon.identity.oauth2.dto.OAuthRevocationResponseDTO)5 OAuthEventInterceptor (org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor)4 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)4 OAuth2Util.buildScopeString (org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString)3 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)2 OAuthTokenPersistenceFactory (org.wso2.carbon.identity.oauth2.dao.OAuthTokenPersistenceFactory)2 TokenManagementDAOImpl (org.wso2.carbon.identity.oauth2.dao.TokenManagementDAOImpl)2 RefreshTokenValidationDataDO (org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO)2 TokenBinding (org.wso2.carbon.identity.oauth2.token.bindings.TokenBinding)2 Map (java.util.Map)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1