Search in sources :

Example 16 with IdentityEventService

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 + "\">"));
        }
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Connection(java.sql.Connection) Matchers.anyString(org.mockito.Matchers.anyString) IOException(java.io.IOException) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) HashSet(java.util.HashSet) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 17 with IdentityEventService

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());
    }
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Matchers.anyString(org.mockito.Matchers.anyString) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 18 with IdentityEventService

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());
    }
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Map(java.util.Map) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 19 with IdentityEventService

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);
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) Matchers.anyString(org.mockito.Matchers.anyString) HttpMethod(javax.ws.rs.HttpMethod) Method(java.lang.reflect.Method) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 20 with IdentityEventService

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);
    }
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) HashMap(java.util.HashMap) IdentityEventException(org.wso2.carbon.identity.event.IdentityEventException) Event(org.wso2.carbon.identity.event.event.Event) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService)

Aggregations

IdentityEventService (org.wso2.carbon.identity.event.services.IdentityEventService)18 HashMap (java.util.HashMap)13 Test (org.testng.annotations.Test)10 IdentityEventException (org.wso2.carbon.identity.event.IdentityEventException)10 Event (org.wso2.carbon.identity.event.event.Event)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 BeforeTest (org.testng.annotations.BeforeTest)8 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 Matchers.anyString (org.mockito.Matchers.anyString)5 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)4 AfterTest (org.testng.annotations.AfterTest)4 OAuthServerConfiguration (org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration)3 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)3 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)3 Method (java.lang.reflect.Method)2 Instant (java.time.Instant)2 Hashtable (java.util.Hashtable)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HttpMethod (javax.ws.rs.HttpMethod)2