Search in sources :

Example 1 with OpenIDConnectUserRPStore

use of org.wso2.carbon.identity.oauth.endpoint.util.OpenIDConnectUserRPStore in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testAuthorizeForAuthenticationResponse.

@Test(dataProvider = "provideAuthenticatedData", groups = "testWithConnection")
public void testAuthorizeForAuthenticationResponse(boolean isResultInRequest, boolean isAuthenticated, Map<ClaimMapping, String> attributes, String errorCode, String errorMsg, String errorUri, Set<String> scopes, String responseMode, String redirectUri, int expected) throws Exception {
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE);
    when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry);
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    AuthenticationResult result = setAuthenticationResult(isAuthenticated, attributes, errorCode, errorMsg, errorUri);
    AuthenticationResult resultInRequest = null;
    AuthenticationResultCacheEntry authResultCacheEntry = null;
    if (isResultInRequest) {
        resultInRequest = result;
    } else {
        authResultCacheEntry = new AuthenticationResultCacheEntry();
        authResultCacheEntry.setResult(result);
    }
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, SESSION_DATA_KEY_VALUE);
    requestAttributes.put(FrameworkConstants.RequestAttribute.AUTH_RESULT, resultInRequest);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    spy(FrameworkUtils.class);
    doReturn(requestCoordinator).when(FrameworkUtils.class, "getRequestCoordinator");
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    spy(IdentityUtil.class);
    doReturn("https://localhost:9443/carbon").when(IdentityUtil.class, "getServerURL", anyString(), anyBoolean(), anyBoolean());
    OAuth2Parameters oAuth2Params = setOAuth2Parameters(scopes, APP_NAME, responseMode, redirectUri);
    oAuth2Params.setClientId(CLIENT_ID_VALUE);
    oAuth2Params.setState(STATE);
    when(loginCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
    when(loginCacheEntry.getLoggedInUser()).thenReturn(result.getSubject());
    mockOAuthServerConfiguration();
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    spy(FrameworkUtils.class);
    doReturn("sample").when(FrameworkUtils.class, "resolveUserIdFromUsername", anyInt(), anyString(), anyString());
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    try (Connection connection = getConnection()) {
        mockStatic(IdentityDatabaseUtil.class);
        when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
        mockStatic(OpenIDConnectUserRPStore.class);
        when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
        when(openIDConnectUserRPStore.hasUserApproved(any(AuthenticatedUser.class), anyString(), anyString())).thenReturn(true);
        mockEndpointUtil(false);
        when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
        mockApplicationManagementService();
        mockEndpointUtil(false);
        when(oAuth2Service.handleAuthenticationFailure(oAuth2Params)).thenReturn(oAuthErrorDTO);
        when(oAuth2ScopeService.hasUserProvidedConsentForAllRequestedScopes(anyString(), anyString(), anyInt(), anyList())).thenReturn(true);
        mockServiceURLBuilder();
        Response response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
        assertEquals(response.getStatus(), expected, "Unexpected HTTP response status");
        if (!isAuthenticated) {
            String expectedState = "name=\"" + OAuthConstants.OAuth20Params.STATE + "\" value=\"" + STATE + "\"";
            assertTrue(response.getEntity().toString().contains(expectedState));
        }
    }
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) 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) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Connection(java.sql.Connection) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AuthenticationResultCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationResultCacheEntry) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 2 with OpenIDConnectUserRPStore

use of org.wso2.carbon.identity.oauth.endpoint.util.OpenIDConnectUserRPStore in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testUserConsentResponse.

@Test(dataProvider = "provideConsentData", groups = "testWithConnection")
public void testUserConsentResponse(String consent, String redirectUrl, Set<String> scopes, int expectedStatus, String oAuthErrorDTODescription, String expectedError) throws Exception {
    initMocks(this);
    spy(FrameworkUtils.class);
    when(authCookie.getValue()).thenReturn("dummyValue");
    doReturn(authCookie).when(FrameworkUtils.class, "getAuthCookie", any());
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    SessionContext sessionContext = new SessionContext();
    sessionContext.addProperty(FrameworkConstants.CREATED_TIMESTAMP, 1479249799770L);
    doReturn(sessionContext).when(FrameworkUtils.class, "getSessionContextFromCache", anyString(), anyString());
    when(openIDConnectClaimFilter.getClaimsFilteredByOIDCScopes(any(), anyString())).thenReturn(Arrays.asList("country"));
    OAuth2AuthzEndpoint.setOpenIDConnectClaimFilter(openIDConnectClaimFilter);
    Set<ExternalClaim> mappings = new HashSet<>();
    ExternalClaim claim = new ExternalClaim(OIDC_DIALECT, "country", "http://wso2.org/country");
    mappings.add(claim);
    when(claimMetadataHandler.getMappingsFromOtherDialectToCarbon(anyString(), any(), anyString())).thenReturn(mappings);
    mockStatic(ClaimMetadataHandler.class);
    when(ClaimMetadataHandler.getInstance()).thenReturn(claimMetadataHandler);
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    SessionDataCacheKey consentDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_CONSENT_VALUE);
    when(sessionDataCache.getValueFromCache(consentDataCacheKey)).thenReturn(consentCacheEntry);
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new ConcurrentHashMap<>();
    requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { SESSION_DATA_KEY_CONSENT_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
    requestParams.put(OAuthConstants.Prompt.CONSENT, new String[] { consent });
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    OAuth2Parameters oAuth2Params = setOAuth2Parameters(scopes, APP_NAME, RESPONSE_MODE_FORM_POST, redirectUrl);
    oAuth2Params.setClientId(CLIENT_ID_VALUE);
    when(consentCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
    when(consentCacheEntry.getLoggedInUser()).thenReturn(new AuthenticatedUser());
    mockStatic(OpenIDConnectUserRPStore.class);
    when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
    doNothing().when(openIDConnectUserRPStore).putUserRPToStore(any(AuthenticatedUser.class), anyString(), anyBoolean(), anyString());
    mockOAuthServerConfiguration();
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    spy(OAuth2Util.class);
    doReturn(new ServiceProvider()).when(OAuth2Util.class, "getServiceProvider", CLIENT_ID_VALUE);
    mockEndpointUtil(true);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    mockApplicationManagementService();
    when(oAuth2Service.handleUserConsentDenial(oAuth2Params)).thenReturn(oAuthErrorDTO);
    when(oAuthErrorDTO.getErrorDescription()).thenReturn(oAuthErrorDTODescription);
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    if (response != null) {
        assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
        MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
        assertNotNull(responseMetadata);
        if (expectedError != null) {
            if (response.getEntity() != null) {
                String htmlPost = response.getEntity().toString();
                assertTrue(htmlPost.contains(expectedError));
            } else {
                CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION));
                assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
                String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
                assertTrue(location.contains(expectedError), "Expected error code not found in URL");
            }
        }
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ExternalClaim(org.wso2.carbon.identity.claim.metadata.mgt.model.ExternalClaim) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) 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) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) 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 3 with OpenIDConnectUserRPStore

use of org.wso2.carbon.identity.oauth.endpoint.util.OpenIDConnectUserRPStore in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testManageOIDCSessionState.

@Test(dataProvider = "provideOidcSessionData", groups = "testWithConnection")
public void testManageOIDCSessionState(Object cookieObject, Object sessionStateObject, String callbackUrl, String responseMode, int expectedStatus, String expectedResult) throws Exception {
    Cookie opBrowserStateCookie = (Cookie) cookieObject;
    Cookie newOpBrowserStateCookie = new Cookie("opbs", "f6454r678776gffdgdsfafa");
    OIDCSessionState previousSessionState = (OIDCSessionState) sessionStateObject;
    AuthenticationResult result = setAuthenticationResult(true, null, null, null, null);
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
    requestParams.put(OAuthConstants.OAuth20Params.PROMPT, new String[] { OAuthConstants.Prompt.LOGIN });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, SESSION_DATA_KEY_VALUE);
    requestAttributes.put(FrameworkConstants.RequestAttribute.AUTH_RESULT, result);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), APP_NAME, responseMode, APP_REDIRECT_URL);
    oAuth2Params.setClientId(CLIENT_ID_VALUE);
    oAuth2Params.setPrompt(OAuthConstants.Prompt.LOGIN);
    mockOAuthServerConfiguration();
    mockEndpointUtil(false);
    when(oAuthServerConfiguration.getOpenIDConnectSkipeUserConsentConfig()).thenReturn(true);
    OAuth2AuthorizeRespDTO authzRespDTO = new OAuth2AuthorizeRespDTO();
    authzRespDTO.setCallbackURI(callbackUrl);
    when(oAuth2Service.authorize(any(OAuth2AuthorizeReqDTO.class))).thenReturn(authzRespDTO);
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    mockStatic(OIDCSessionManagementUtil.class);
    when(OIDCSessionManagementUtil.getOPBrowserStateCookie(any(HttpServletRequest.class))).thenReturn(opBrowserStateCookie);
    when(OIDCSessionManagementUtil.addOPBrowserStateCookie(any(HttpServletResponse.class))).thenReturn(newOpBrowserStateCookie);
    when(OIDCSessionManagementUtil.addOPBrowserStateCookie(any(HttpServletResponse.class), any(HttpServletRequest.class), any(String.class), any(String.class))).thenReturn(newOpBrowserStateCookie);
    when(OIDCSessionManagementUtil.getSessionManager()).thenReturn(oidcSessionManager);
    when(oidcSessionManager.getOIDCSessionState(anyString(), anyString())).thenReturn(previousSessionState);
    when(OIDCSessionManagementUtil.getSessionStateParam(anyString(), anyString(), anyString())).thenReturn("sessionStateValue");
    when(OIDCSessionManagementUtil.addSessionStateToURL(anyString(), anyString(), anyString())).thenCallRealMethod();
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE);
    when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry);
    when(loginCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
    when(loginCacheEntry.getLoggedInUser()).thenReturn(result.getSubject());
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    mockStatic(OpenIDConnectUserRPStore.class);
    when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
    when(openIDConnectUserRPStore.hasUserApproved(any(AuthenticatedUser.class), anyString(), anyString())).thenReturn(true);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    mockApplicationManagementService();
    spy(FrameworkUtils.class);
    doReturn("sample").when(FrameworkUtils.class, "resolveUserIdFromUsername", anyInt(), anyString(), anyString());
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    spy(IdentityTenantUtil.class);
    doReturn(MultitenantConstants.SUPER_TENANT_ID).when(IdentityTenantUtil.class, "getTenantId", anyString());
    doReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME).when(IdentityTenantUtil.class, "getTenantDomain", anyInt());
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Authorization response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
    MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
    assertNotNull(responseMetadata, "Response metadata is null");
    if (response.getStatus() != HttpServletResponse.SC_OK) {
        assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
        String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
        assertTrue(location.contains(expectedResult), "Expected redirect URL is not returned");
    } else {
        assertTrue(response.getEntity().toString().contains(expectedResult), "Expected redirect URL is not returned");
    }
}
Also used : Cookie(javax.servlet.http.Cookie) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) HttpServletResponse(javax.servlet.http.HttpServletResponse) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) HttpServletRequest(javax.servlet.http.HttpServletRequest) 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) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) OIDCSessionState(org.wso2.carbon.identity.oidc.session.OIDCSessionState) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 4 with OpenIDConnectUserRPStore

use of org.wso2.carbon.identity.oauth.endpoint.util.OpenIDConnectUserRPStore in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testHandleUserConsent.

@Test(dataProvider = "provideUserConsentData", groups = "testWithConnection")
public void testHandleUserConsent(boolean isRespDTONull, String consent, boolean skipConsent, String errorCode, String authCode, String accessToken, String idToken, String responseType, String responseMode, String authenticatedIdps, String state, int expectedStatus, String expectedLocation) throws Exception {
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();
    requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { SESSION_DATA_KEY_CONSENT_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
    requestParams.put(OAuthConstants.Prompt.CONSENT, new String[] { consent });
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    SessionDataCacheKey consentDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_CONSENT_VALUE);
    when(sessionDataCache.getValueFromCache(consentDataCacheKey)).thenReturn(consentCacheEntry);
    OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<String>(), APP_NAME, responseMode, APP_REDIRECT_URL);
    oAuth2Params.setResponseType(responseType);
    oAuth2Params.setState(state);
    oAuth2Params.setClientId(CLIENT_ID_VALUE);
    when(consentCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
    when(consentCacheEntry.getLoggedInUser()).thenReturn(new AuthenticatedUser());
    when(consentCacheEntry.getAuthenticatedIdPs()).thenReturn(authenticatedIdps);
    OAuth2AuthorizeRespDTO authzRespDTO = null;
    if (!isRespDTONull) {
        authzRespDTO = new OAuth2AuthorizeRespDTO();
        authzRespDTO.setAuthorizationCode(authCode);
        authzRespDTO.setCallbackURI(APP_REDIRECT_URL);
        authzRespDTO.setAccessToken(accessToken);
        authzRespDTO.setIdToken(idToken);
        authzRespDTO.setErrorCode(errorCode);
        if (OAuthConstants.ID_TOKEN.equals(responseType) && idToken == null) {
            authzRespDTO.setCallbackURI(APP_REDIRECT_URL + "?");
        }
    }
    mockEndpointUtil(false);
    when(oAuth2Service.authorize(any(OAuth2AuthorizeReqDTO.class))).thenReturn(authzRespDTO);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    mockStatic(OpenIDConnectUserRPStore.class);
    when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
    doNothing().when(openIDConnectUserRPStore).putUserRPToStore(any(AuthenticatedUser.class), anyString(), anyBoolean(), anyString());
    when(oAuthServerConfiguration.getOpenIDConnectSkipeUserConsentConfig()).thenReturn(skipConsent);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(oAuthServerConfiguration.getAuthorizationCodeValidityPeriodInSeconds()).thenReturn(300L);
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getServiceProvider(CLIENT_ID_VALUE)).thenReturn(new ServiceProvider());
    mockApplicationManagementService();
    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);
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Authorization response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
    if (expectedLocation != null) {
        MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
        assertNotNull(responseMetadata, "Response metadata is null");
        assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
        String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
        assertTrue(location.contains(expectedLocation), "Unexpected redirect url in the response");
        if (errorCode != null) {
            assertTrue(location.contains(errorCode), "Expected error code not found in URL");
        }
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) 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) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 5 with OpenIDConnectUserRPStore

use of org.wso2.carbon.identity.oauth.endpoint.util.OpenIDConnectUserRPStore in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testDoUserAuthz.

@Test(dataProvider = "provideDataForUserAuthz", groups = "testWithConnection")
public void testDoUserAuthz(String prompt, String idTokenHint, boolean hasUserApproved, boolean skipConsent, boolean idTokenHintValid, String loggedInUser, String idTokenHintSubject, String errorCode) throws Exception {
    AuthenticationResult result = setAuthenticationResult(true, null, null, null, null);
    result.getSubject().setAuthenticatedSubjectIdentifier(loggedInUser);
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, SESSION_DATA_KEY_VALUE);
    requestAttributes.put(FrameworkConstants.RequestAttribute.AUTH_RESULT, result);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<String>(), APP_NAME, null, APP_REDIRECT_URL);
    oAuth2Params.setClientId(CLIENT_ID_VALUE);
    oAuth2Params.setPrompt(prompt);
    oAuth2Params.setIDTokenHint(idTokenHint);
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE);
    when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry);
    when(loginCacheEntry.getLoggedInUser()).thenReturn(result.getSubject());
    when(loginCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
    mockEndpointUtil(false);
    when(oAuth2ScopeService.hasUserProvidedConsentForAllRequestedScopes(anyString(), anyString(), anyInt(), anyList())).thenReturn(hasUserApproved);
    mockOAuthServerConfiguration();
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    mockStatic(OpenIDConnectUserRPStore.class);
    when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
    when(openIDConnectUserRPStore.hasUserApproved(any(AuthenticatedUser.class), anyString(), anyString())).thenReturn(hasUserApproved);
    spy(OAuth2Util.class);
    doReturn(idTokenHintValid).when(OAuth2Util.class, "validateIdToken", anyString());
    mockStatic(SignedJWT.class);
    if ("invalid".equals(idTokenHint)) {
        when(SignedJWT.parse(anyString())).thenThrow(new ParseException("error", 1));
    } else {
        when(SignedJWT.parse(anyString())).thenReturn(signedJWT);
    }
    JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder();
    jwtClaimsSetBuilder.subject(idTokenHintSubject);
    JWTClaimsSet jwtClaimsSet = jwtClaimsSetBuilder.build();
    when(signedJWT.getJWTClaimsSet()).thenReturn(jwtClaimsSet);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    mockApplicationManagementService();
    spy(FrameworkUtils.class);
    doReturn("sample").when(FrameworkUtils.class, "resolveUserIdFromUsername", anyInt(), anyString(), anyString());
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    spy(IdentityTenantUtil.class);
    doReturn(MultitenantConstants.SUPER_TENANT_ID).when(IdentityTenantUtil.class, "getTenantId", anyString());
    doReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME).when(IdentityTenantUtil.class, "getTenantDomain", anyInt());
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Authorization response is null");
    assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND, "Unexpected HTTP response status");
    if (errorCode != null) {
        MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
        assertNotNull(responseMetadata, "Response metadata is null");
        assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
        String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
        assertTrue(location.contains(errorCode), "Expected error code not found in URL");
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) 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) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) ParseException(java.text.ParseException) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

HashMap (java.util.HashMap)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)5 Response (javax.ws.rs.core.Response)5 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)5 Matchers.anyString (org.mockito.Matchers.anyString)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 AfterTest (org.testng.annotations.AfterTest)5 BeforeTest (org.testng.annotations.BeforeTest)5 Test (org.testng.annotations.Test)5 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)5 SessionDataCacheKey (org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey)5 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)5 OAuth2ScopeConsentResponse (org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse)5 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)5 InvalidRequestParentException (org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException)4 InvalidRequestExceptionMapper (org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper)4 AuthenticationResult (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult)3 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)2