Search in sources :

Example 1 with SessionDataCacheKey

use of org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey in project identity-inbound-auth-oauth by wso2-extensions.

the class EndpointUtil method getUserConsentURL.

/**
 * Returns the consent page URL.
 *
 * @param params            OAuth2 Parameters.
 * @param loggedInUser      The logged in user
 * @param isOIDC            Whether the flow is an OIDC or not.
 * @param oAuthMessage      oAuth Message.
 * @return                  The consent url.
 */
public static String getUserConsentURL(OAuth2Parameters params, String loggedInUser, String sessionDataKey, boolean isOIDC, OAuthMessage oAuthMessage) throws OAuthSystemException {
    String queryString = "";
    if (log.isDebugEnabled()) {
        log.debug("Received Session Data Key is :  " + sessionDataKey);
        if (params == null) {
            log.debug("Received OAuth2 params are Null for UserConsentURL");
        }
    }
    SessionDataCache sessionDataCache = SessionDataCache.getInstance();
    SessionDataCacheEntry entry;
    if (oAuthMessage != null) {
        entry = oAuthMessage.getResultFromLogin();
    } else {
        entry = sessionDataCache.getValueFromCache(new SessionDataCacheKey(sessionDataKey));
    }
    AuthenticatedUser user = null;
    String consentPage = null;
    String sessionDataKeyConsent = UUID.randomUUID().toString();
    try {
        if (entry != null && entry.getQueryString() != null) {
            if (entry.getQueryString().contains(REQUEST_URI) && params != null) {
                // When request_uri requests come without redirect_uri, we need to append it to the SPQueryParams
                // to be used in storing consent data
                entry.setQueryString(entry.getQueryString() + "&" + PROP_REDIRECT_URI + "=" + params.getRedirectURI());
            }
            queryString = URLEncoder.encode(entry.getQueryString(), UTF_8);
        }
        if (isOIDC) {
            consentPage = OAuth2Util.OAuthURL.getOIDCConsentPageUrl();
        } else {
            consentPage = OAuth2Util.OAuthURL.getOAuth2ConsentPageUrl();
        }
        if (params != null) {
            consentPage += "?" + OAuthConstants.OIDC_LOGGED_IN_USER + "=" + URLEncoder.encode(loggedInUser, UTF_8) + "&application=";
            if (StringUtils.isNotEmpty(params.getDisplayName())) {
                consentPage += URLEncoder.encode(params.getDisplayName(), UTF_8);
            } else {
                consentPage += URLEncoder.encode(params.getApplicationName(), UTF_8);
            }
            consentPage += "&tenantDomain=" + getSPTenantDomainFromClientId(params.getClientId());
            if (entry != null) {
                user = entry.getLoggedInUser();
            }
            setConsentRequiredScopesToOAuthParams(user, params);
            Set<String> consentRequiredScopesSet = params.getConsentRequiredScopes();
            String consentRequiredScopes = StringUtils.EMPTY;
            if (CollectionUtils.isNotEmpty(consentRequiredScopesSet)) {
                consentRequiredScopes = String.join(" ", consentRequiredScopesSet).trim();
            }
            consentPage = consentPage + "&" + OAuthConstants.OAuth20Params.SCOPE + "=" + URLEncoder.encode(consentRequiredScopes, UTF_8) + "&" + OAuthConstants.SESSION_DATA_KEY_CONSENT + "=" + URLEncoder.encode(sessionDataKeyConsent, UTF_8) + "&" + "&spQueryParams=" + queryString;
            if (entry != null) {
                consentPage = FrameworkUtils.getRedirectURLWithFilteredParams(consentPage, entry.getEndpointParams());
                entry.setValidityPeriod(TimeUnit.MINUTES.toNanos(IdentityUtil.getTempDataCleanUpTimeout()));
                sessionDataCache.addToCache(new SessionDataCacheKey(sessionDataKeyConsent), entry);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Cache Entry is Null from SessionDataCache.");
                }
            }
        } else {
            throw new OAuthSystemException("Error while retrieving the application name");
        }
    } catch (UnsupportedEncodingException e) {
        throw new OAuthSystemException("Error while encoding the url", e);
    }
    return consentPage;
}
Also used : SessionDataCache(org.wso2.carbon.identity.oauth.cache.SessionDataCache) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 2 with SessionDataCacheKey

use of org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method addDataToSessionCache.

private void addDataToSessionCache(OAuthMessage oAuthMessage, OAuth2Parameters params, String sessionDataKey) {
    SessionDataCacheKey cacheKey = new SessionDataCacheKey(sessionDataKey);
    SessionDataCacheEntry sessionDataCacheEntryNew = new SessionDataCacheEntry();
    sessionDataCacheEntryNew.setoAuth2Parameters(params);
    sessionDataCacheEntryNew.setQueryString(oAuthMessage.getRequest().getQueryString());
    if (oAuthMessage.getRequest().getParameterMap() != null) {
        sessionDataCacheEntryNew.setParamMap(new ConcurrentHashMap<>(oAuthMessage.getRequest().getParameterMap()));
    }
    sessionDataCacheEntryNew.setValidityPeriod(TimeUnit.MINUTES.toNanos(IdentityUtil.getTempDataCleanUpTimeout()));
    SessionDataCache.getInstance().addToCache(cacheKey, sessionDataCacheEntryNew);
}
Also used : SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey)

Example 3 with SessionDataCacheKey

use of org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey 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 4 with SessionDataCacheKey

use of org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey 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 5 with SessionDataCacheKey

use of org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey 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)

Aggregations

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