use of org.wso2.carbon.identity.event.services.IdentityEventService in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method testAuthorize.
@Test(dataProvider = "provideParams", groups = "testWithConnection")
public void testAuthorize(Object flowStatusObject, String[] clientId, String sessionDataKayConsent, String toCommonAuth, String scope, String sessionDataKey, Exception e, int expectedStatus, String expectedError, String responseMode) throws Exception {
AuthenticatorFlowStatus flowStatus = (AuthenticatorFlowStatus) flowStatusObject;
Map<String, String[]> requestParams = new HashMap<>();
Map<String, Object> requestAttributes = new HashMap<>();
if (clientId != null) {
requestParams.put(CLIENT_ID, clientId);
}
requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { sessionDataKayConsent });
requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { toCommonAuth });
requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { scope });
if (StringUtils.equals(responseMode, RESPONSE_MODE_FORM_POST)) {
requestParams.put(RESPONSE_MODE, new String[] { RESPONSE_MODE_FORM_POST });
}
requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, flowStatus);
requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
if (e instanceof OAuthProblemException) {
requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
}
mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
mockStatic(OAuth2Util.OAuthURL.class);
when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
spy(FrameworkUtils.class);
doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
doNothing().when(FrameworkUtils.class, "endTenantFlow");
mockStatic(IdentityTenantUtil.class);
mockStatic(LoggerUtils.class);
when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
IdentityEventService eventServiceMock = mock(IdentityEventService.class);
mockStatic(CentralLogMgtServiceComponentHolder.class);
when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
mockStatic(SessionDataCache.class);
when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE);
SessionDataCacheKey consentDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_CONSENT_VALUE);
when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry);
when(sessionDataCache.getValueFromCache(consentDataCacheKey)).thenReturn(consentCacheEntry);
when(loginCacheEntry.getoAuth2Parameters()).thenReturn(setOAuth2Parameters(new HashSet<>(Collections.singletonList(OAuthConstants.Scope.OPENID)), APP_NAME, null, null));
mockOAuthServerConfiguration();
mockEndpointUtil(false);
when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
if (ArrayUtils.isNotEmpty(clientId) && (clientId[0].equalsIgnoreCase("invalidId") || clientId[0].equalsIgnoreCase(INACTIVE_CLIENT_ID_VALUE) || StringUtils.isEmpty(clientId[0]))) {
when(oAuth2Service.validateClientInfo(clientId[0], APP_REDIRECT_URL)).thenCallRealMethod();
} else {
when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(oAuth2ClientValidationResponseDTO);
when(oAuth2ClientValidationResponseDTO.isValidClient()).thenReturn(true);
}
if (e instanceof IOException) {
CommonAuthenticationHandler handler = mock(CommonAuthenticationHandler.class);
doThrow(e).when(handler).doGet(any(), any());
whenNew(CommonAuthenticationHandler.class).withNoArguments().thenReturn(handler);
}
Response response;
try (Connection connection = getConnection()) {
mockStatic(IdentityDatabaseUtil.class);
when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
mockServiceURLBuilder();
try {
response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
} catch (InvalidRequestParentException ire) {
InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
response = invalidRequestExceptionMapper.toResponse(ire);
}
}
if (!StringUtils.equals(responseMode, RESPONSE_MODE_FORM_POST)) {
assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
assertNotNull(responseMetadata, "HTTP response metadata is null");
if (expectedStatus == HttpServletResponse.SC_FOUND) {
if (expectedError != null) {
List<Object> redirectPath = responseMetadata.get(HTTPConstants.HEADER_LOCATION);
if (CollectionUtils.isNotEmpty(redirectPath)) {
String location = String.valueOf(redirectPath.get(0));
assertTrue(location.contains(expectedError), "Expected error code not found in URL");
} else {
assertNotNull(response.getEntity(), "Response entity is null");
assertTrue(response.getEntity().toString().contains(expectedError), "Expected error code not found response entity");
}
} else {
// This is the case where a redirect outside happens.
List<Object> redirectPath = responseMetadata.get(HTTPConstants.HEADER_LOCATION);
assertTrue(CollectionUtils.isNotEmpty(redirectPath));
String location = String.valueOf(redirectPath.get(0));
assertNotNull(location);
assertFalse(location.contains("error"), "Expected no errors in the redirect url, but found one.");
}
}
} else {
if (expectedError != null) {
// Check if the error response is of form post mode
assertTrue(response.getEntity().toString().contains("<form method=\"post\" action=\"" + APP_REDIRECT_URL + "\">"));
}
}
}
use of org.wso2.carbon.identity.event.services.IdentityEventService in project identity-inbound-auth-oauth by wso2-extensions.
the class OIDCRequestObjectUtilTest method testBuildRequestObjectTest.
@Test(dataProvider = "TestBuildRequestObjectTest")
public void testBuildRequestObjectTest(String requestObjectString, Map<String, Object> claims, boolean isSigned, boolean isEncrypted, boolean exceptionNotExpected, String errorMsg) throws Exception {
OAuth2Parameters oAuth2Parameters = new OAuth2Parameters();
oAuth2Parameters.setTenantDomain("carbon.super");
oAuth2Parameters.setClientId(TEST_CLIENT_ID_1);
OAuthAuthzRequest oAuthAuthzRequest = mock(OAuthAuthzRequest.class);
IdentityEventService eventServiceMock = mock(IdentityEventService.class);
when(oAuthAuthzRequest.getParam(Constants.REQUEST)).thenReturn(requestObjectString);
mockStatic(CentralLogMgtServiceComponentHolder.class);
when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
OAuthServerConfiguration oauthServerConfigurationMock = mock(OAuthServerConfiguration.class);
mockStatic(OAuthServerConfiguration.class);
when(OAuthServerConfiguration.getInstance()).thenReturn(oauthServerConfigurationMock);
mockStatic(OAuth2Util.class);
when(OAuth2Util.getTenantId("carbon.super")).thenReturn(-1234);
when((OAuth2Util.getPrivateKey(anyString(), anyInt()))).thenReturn(rsaPrivateKey);
when(OAuth2Util.getX509CertOfOAuthApp(TEST_CLIENT_ID_1, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)).thenReturn(clientKeyStore.getCertificate("wso2carbon"));
OAuthAppDO oAuthAppDO = new OAuthAppDO();
when(OAuth2Util.getAppInformationByClientId(TEST_CLIENT_ID_1)).thenReturn(oAuthAppDO);
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
RequestObjectValidator requestObjectValidator = PowerMockito.spy(new RequestObjectValidatorImpl());
when((oauthServerConfigurationMock.getRequestObjectValidator())).thenReturn(requestObjectValidator);
PowerMockito.doReturn(SOME_SERVER_URL).when(requestObjectValidator, "getTokenEpURL", anyString());
RequestParamRequestObjectBuilder requestParamRequestObjectBuilder = new RequestParamRequestObjectBuilder();
Map<String, RequestObjectBuilder> requestObjectBuilderMap = new HashMap<>();
requestObjectBuilderMap.put(REQUEST_PARAM_VALUE_BUILDER, requestParamRequestObjectBuilder);
requestObjectBuilderMap.put(REQUEST_URI_PARAM_VALUE_BUILDER, null);
when((oauthServerConfigurationMock.getRequestObjectBuilders())).thenReturn(requestObjectBuilderMap);
try {
OIDCRequestObjectUtil.buildRequestObject(oAuthAuthzRequest, oAuth2Parameters);
} catch (RequestObjectException e) {
Assert.assertFalse(exceptionNotExpected, errorMsg + " Request Object Building failed due to " + e.getErrorMessage());
}
}
use of org.wso2.carbon.identity.event.services.IdentityEventService in project identity-inbound-auth-oauth by wso2-extensions.
the class RequestParamRequestObjectBuilderTest method buildRequestObjectTest.
@Test(dataProvider = "TestBuildRequestObjectTest")
public void buildRequestObjectTest(String requestObjectString, Map<String, Object> claims, boolean isSigned, boolean isEncrypted, boolean exceptionNotExpected, String errorMsg) throws Exception {
mockStatic(IdentityUtil.class);
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
IdentityEventService eventServiceMock = mock(IdentityEventService.class);
mockStatic(CentralLogMgtServiceComponentHolder.class);
when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
when(IdentityUtil.getServerURL(anyString(), anyBoolean(), anyBoolean())).thenReturn("some-server-url");
OAuth2Parameters oAuth2Parameters = new OAuth2Parameters();
oAuth2Parameters.setTenantDomain("carbon.super");
oAuth2Parameters.setClientId(TEST_CLIENT_ID_1);
OAuthServerConfiguration oauthServerConfigurationMock = mock(OAuthServerConfiguration.class);
mockStatic(OAuthServerConfiguration.class);
when(OAuthServerConfiguration.getInstance()).thenReturn(oauthServerConfigurationMock);
mockStatic(RequestObjectValidatorImpl.class);
PowerMockito.spy(RequestObjectValidatorImpl.class);
rsaPrivateKey = (RSAPrivateKey) wso2KeyStore.getKey("wso2carbon", "wso2carbon".toCharArray());
mockStatic(OAuth2Util.class);
when(OAuth2Util.getTenantId("carbon.super")).thenReturn(-1234);
when((OAuth2Util.getPrivateKey(anyString(), anyInt()))).thenReturn(rsaPrivateKey);
when(OAuth2Util.getX509CertOfOAuthApp(TEST_CLIENT_ID_1, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)).thenReturn(clientKeyStore.getCertificate("wso2carbon"));
RequestObjectValidator requestObjectValidator = new RequestObjectValidatorImpl();
when((oauthServerConfigurationMock.getRequestObjectValidator())).thenReturn(requestObjectValidator);
RequestObject requestObject;
RequestParamRequestObjectBuilder requestParamRequestObjectBuilder = new RequestParamRequestObjectBuilder();
try {
requestObject = requestParamRequestObjectBuilder.buildRequestObject(requestObjectString, oAuth2Parameters);
Assert.assertEquals(requestObject.isSigned(), isSigned, errorMsg);
if (claims != null && !claims.isEmpty()) {
for (Map.Entry entry : claims.entrySet()) {
Assert.assertEquals(requestObject.getClaim(entry.getKey().toString()), entry.getValue(), "Request object claim:" + entry.getKey() + " is not properly set.");
}
}
} catch (RequestObjectException e) {
Assert.assertFalse(exceptionNotExpected, errorMsg + "Building failed due to " + e.getMessage());
}
}
use of org.wso2.carbon.identity.event.services.IdentityEventService in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method testGetLoginTenantDomain.
@Test(dataProvider = "provideGetLoginTenantDomainData")
public void testGetLoginTenantDomain(boolean isTenantedSessionsEnabled, String loginDomain, String expectedDomain) throws Exception {
mockOAuthServerConfiguration();
mockStatic(LoggerUtils.class);
when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
spy(FrameworkUtils.class);
doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
doNothing().when(FrameworkUtils.class, "endTenantFlow");
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
IdentityEventService eventServiceMock = mock(IdentityEventService.class);
mockStatic(CentralLogMgtServiceComponentHolder.class);
when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
if (isTenantedSessionsEnabled) {
when(IdentityTenantUtil.isTenantedSessionsEnabled()).thenReturn(true);
} else {
when(IdentityTenantUtil.isTenantedSessionsEnabled()).thenReturn(false);
}
mockStatic(IdentityDatabaseUtil.class);
when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
Map<String, String[]> requestParams = new HashMap();
Map<String, Object> requestAttributes = new HashMap();
requestParams.put(FrameworkConstants.RequestParams.LOGIN_TENANT_DOMAIN, new String[] { loginDomain });
mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
when(oAuthMessage.getRequest()).thenReturn(httpServletRequest);
Method getLoginTenantDomain = authzEndpointObject.getClass().getDeclaredMethod("getLoginTenantDomain", OAuthMessage.class, String.class);
getLoginTenantDomain.setAccessible(true);
String tenantDomain = (String) getLoginTenantDomain.invoke(authzEndpointObject, oAuthMessage, CLIENT_ID_VALUE);
assertEquals(tenantDomain, expectedDomain);
}
use of org.wso2.carbon.identity.event.services.IdentityEventService in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2TokenUtil method postIssueAccessToken.
/**
* Uses to update access token details in the request object reference table.
*
* @param tokenId token id
* @param sessionDataKey session data key
* @throws IdentityOAuth2Exception
*/
public static void postIssueAccessToken(String tokenId, String sessionDataKey) throws IdentityOAuth2Exception {
String eventName = OIDCConstants.Event.POST_ISSUE_ACCESS_TOKEN;
HashMap<String, Object> properties = new HashMap<>();
properties.put(OIDCConstants.Event.TOKEN_ID, tokenId);
properties.put(OIDCConstants.Event.SESSION_DATA_KEY, sessionDataKey);
Event requestObjectPersistanceEvent = new Event(eventName, properties);
IdentityEventService identityEventService = OpenIDConnectServiceComponentHolder.getIdentityEventService();
try {
if (identityEventService != null) {
identityEventService.handleEvent(requestObjectPersistanceEvent);
if (log.isDebugEnabled()) {
log.debug("The event " + eventName + " triggered after the access token " + tokenId + " is issued.");
}
}
} catch (IdentityEventException e) {
throw new IdentityOAuth2Exception("Error while invoking the request object persistance handler when " + "issuing the access token id: " + tokenId);
}
}
Aggregations