Search in sources :

Example 6 with CommonAuthenticationHandler

use of org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler 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)

Aggregations

CommonAuthenticationHandler (org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 HashMap (java.util.HashMap)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Matchers.anyString (org.mockito.Matchers.anyString)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 AfterTest (org.testng.annotations.AfterTest)3 BeforeTest (org.testng.annotations.BeforeTest)3 Test (org.testng.annotations.Test)3 CommonAuthRequestWrapper (org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper)3 CommonAuthResponseWrapper (org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)3 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)3 IOException (java.io.IOException)2 ServletException (javax.servlet.ServletException)2 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)2 Response (javax.ws.rs.core.Response)2 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)2 AuthenticatorFlowStatus (org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus)2 IdentityEventService (org.wso2.carbon.identity.event.services.IdentityEventService)2 InvalidRequestParentException (org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException)2