use of org.wso2.carbon.identity.oauth.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");
}
}
}
use of org.wso2.carbon.identity.oauth.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);
}
}
use of org.wso2.carbon.identity.oauth.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);
}
}
}
use of org.wso2.carbon.identity.oauth.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);
}
}
}
}
use of org.wso2.carbon.identity.oauth.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();
}
Aggregations