Search in sources :

Example 46 with OAuth2Parameters

use of org.wso2.carbon.identity.oauth2.model.OAuth2Parameters in project identity-inbound-auth-oauth by wso2-extensions.

the class EndpointUtilTest method testGetErrorRedirectURL.

@Test(dataProvider = "provideErrorRedirectData")
public void testGetErrorRedirectURL(boolean isImplicitResponse, boolean isImplicitFragment, Object oAuth2ParamObject, Object exeObject, String expected, boolean isDebugOn) throws Exception {
    setMockedLog(isDebugOn);
    OAuth2Parameters parameters = (OAuth2Parameters) oAuth2ParamObject;
    OAuthProblemException exception = OAuthProblemException.error("OAuthProblemExceptionErrorMessage");
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(mockedOAuthServerConfiguration);
    when(mockedOAuthServerConfiguration.isImplicitErrorFragment()).thenReturn(isImplicitFragment);
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.isImplicitResponseType(anyString())).thenReturn(isImplicitResponse);
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    mockStatic(OAuthResponse.OAuthErrorResponseBuilder.class);
    whenNew(OAuthResponse.OAuthErrorResponseBuilder.class).withArguments(anyInt()).thenReturn(mockedOAuthErrorResponseBuilder);
    when(mockedOAuthErrorResponseBuilder.error(any(OAuthProblemException.class))).thenReturn(mockedOAuthErrorResponseBuilder);
    when(mockedOAuthErrorResponseBuilder.location(anyString())).thenReturn(mockedOAuthErrorResponseBuilder);
    when(mockedOAuthErrorResponseBuilder.setState(anyString())).thenReturn(mockedOAuthErrorResponseBuilder);
    when(mockedOAuthErrorResponseBuilder.setParam(anyString(), anyString())).thenReturn(mockedOAuthErrorResponseBuilder);
    if (exeObject != null) {
        OAuthSystemException oAuthSystemException = (OAuthSystemException) exeObject;
        when(mockedOAuthErrorResponseBuilder.buildQueryMessage()).thenThrow(oAuthSystemException);
    } else {
        when(mockedOAuthErrorResponseBuilder.buildQueryMessage()).thenReturn(mockedOAuthResponse);
    }
    when(mockedOAuthResponse.getLocationUri()).thenReturn("http://localhost:8080/location");
    String url = EndpointUtil.getErrorRedirectURL(exception, parameters);
    Assert.assertTrue(url.contains(expected), "Expected error redirect url not returned");
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) Matchers.anyString(org.mockito.Matchers.anyString) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 47 with OAuth2Parameters

use of org.wso2.carbon.identity.oauth2.model.OAuth2Parameters in project identity-inbound-auth-oauth by wso2-extensions.

the class EndpointUtilTest method testGetUserConsentURL.

@Test(dataProvider = "provideDataForUserConsentURL")
public void testGetUserConsentURL(Object oAuth2ParamObject, boolean isOIDC, boolean cacheEntryExists, boolean throwError, String queryString, boolean isDebugEnabled) throws Exception {
    setMockedLog(isDebugEnabled);
    OAuth2Parameters parameters = (OAuth2Parameters) oAuth2ParamObject;
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(mockedOAuthServerConfiguration);
    EndpointUtil.setOauthServerConfiguration(mockedOAuthServerConfiguration);
    when(mockedOAuthServerConfiguration.isDropUnregisteredScopes()).thenReturn(false);
    EndpointUtil.setOAuth2ScopeService(oAuth2ScopeService);
    when(oAuth2ScopeService.getUserConsentForApp(anyString(), anyString(), anyInt())).thenReturn(oAuth2ScopeConsentResponse);
    mockStatic(OAuth2Util.class);
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOIDCConsentPageUrl()).thenReturn(OIDC_CONSENT_PAGE_URL);
    when(OAuth2Util.OAuthURL.getOAuth2ConsentPageUrl()).thenReturn(OAUTH2_CONSENT_PAGE_URL);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockStatic(FrameworkUtils.class);
    when(FrameworkUtils.resolveUserIdFromUsername(anyInt(), anyString(), anyString())).thenReturn("sample");
    when(FrameworkUtils.getRedirectURLWithFilteredParams(anyString(), anyMap())).then(i -> i.getArgumentAt(0, String.class));
    mockStatic(OAuth2Util.class);
    spy(EndpointUtil.class);
    doReturn("sampleId").when(EndpointUtil.class, "getAppIdFromClientId", anyString());
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(mockedSessionDataCache);
    if (cacheEntryExists) {
        when(mockedSessionDataCache.getValueFromCache(any(SessionDataCacheKey.class))).thenReturn(mockedSessionDataCacheEntry);
        when(mockedSessionDataCacheEntry.getQueryString()).thenReturn(queryString);
        when(mockedSessionDataCacheEntry.getLoggedInUser()).thenReturn(user);
        when(mockedSessionDataCacheEntry.getEndpointParams()).thenReturn(new HashMap<>());
    } else {
        when(mockedSessionDataCache.getValueFromCache(any(SessionDataCacheKey.class))).thenReturn(null);
    }
    EndpointUtil.setOAuthAdminService(mockedOAuthAdminService);
    when(mockedOAuthAdminService.getScopeNames()).thenReturn(new String[0]);
    JDBCPermissionBasedInternalScopeValidator scopeValidatorSpy = PowerMockito.spy(new JDBCPermissionBasedInternalScopeValidator());
    doNothing().when(scopeValidatorSpy, method(JDBCPermissionBasedInternalScopeValidator.class, "endTenantFlow")).withNoArguments();
    when(scopeValidatorSpy, method(JDBCPermissionBasedInternalScopeValidator.class, "getUserAllowedScopes", AuthenticatedUser.class, String[].class, String.class)).withArguments(any(AuthenticatedUser.class), any(), anyString()).thenReturn(getScopeList());
    PowerMockito.whenNew(JDBCPermissionBasedInternalScopeValidator.class).withNoArguments().thenReturn(scopeValidatorSpy);
    String consentUrl;
    try {
        consentUrl = EndpointUtil.getUserConsentURL(parameters, username, sessionDataKey, isOIDC);
        if (isOIDC) {
            Assert.assertTrue(consentUrl.contains(OIDC_CONSENT_PAGE_URL), "Incorrect consent page url for OIDC");
        } else {
            Assert.assertTrue(consentUrl.contains(OAUTH2_CONSENT_PAGE_URL), "Incorrect consent page url for OAuth");
        }
        Assert.assertTrue(consentUrl.contains(URLEncoder.encode(username, "UTF-8")), "loggedInUser parameter value is not found in url");
        Assert.assertTrue(consentUrl.contains(URLEncoder.encode("TestApplication", "ISO-8859-1")), "application parameter value is not found in url");
        List<NameValuePair> nameValuePairList = URLEncodedUtils.parse(consentUrl, StandardCharsets.UTF_8);
        Optional<NameValuePair> optionalScope = nameValuePairList.stream().filter(nameValuePair -> nameValuePair.getName().equals("scope")).findAny();
        Assert.assertTrue(optionalScope.isPresent());
        NameValuePair scopeNameValuePair = optionalScope.get();
        String[] scopeArray = scopeNameValuePair.getValue().split(" ");
        Assert.assertTrue(ArrayUtils.contains(scopeArray, "scope2"), "scope parameter value " + "is not found in url");
        Assert.assertTrue(ArrayUtils.contains(scopeArray, "internal_login"), "internal_login " + "scope parameter value is not found in url");
        Assert.assertFalse(ArrayUtils.contains(scopeArray, "SYSTEM"), "SYSTEM scope" + "parameter should not contain in the url.");
        if (queryString != null && cacheEntryExists) {
            Assert.assertTrue(consentUrl.contains(queryString), "spQueryParams value is not found in url");
        }
    } catch (OAuthSystemException e) {
        Assert.assertTrue(e.getMessage().contains("Error while retrieving the application name"));
    }
}
Also used : OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Scope(org.wso2.carbon.identity.oauth2.bean.Scope) Arrays(java.util.Arrays) DefaultOIDCProcessor(org.wso2.carbon.identity.discovery.DefaultOIDCProcessor) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Test(org.testng.annotations.Test) ServiceURL(org.wso2.carbon.identity.core.ServiceURL) PowerMockito.doNothing(org.powermock.api.mockito.PowerMockito.doNothing) AuthenticationRequestCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry) Map(java.util.Map) URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) Matchers.anyInt(org.mockito.Matchers.anyInt) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) PowerMockito.whenNew(org.powermock.api.mockito.PowerMockito.whenNew) OAuthAdminServiceImpl(org.wso2.carbon.identity.oauth.OAuthAdminServiceImpl) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) OAuthClientException(org.wso2.carbon.identity.oauth.common.exception.OAuthClientException) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) Set(java.util.Set) PowerMockito.doReturn(org.powermock.api.mockito.PowerMockito.doReturn) HashedMap(org.apache.commons.collections.map.HashedMap) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.any(org.mockito.Matchers.any) List(java.util.List) PowerMockito.mock(org.powermock.api.mockito.PowerMockito.mock) OAuth2Service(org.wso2.carbon.identity.oauth2.OAuth2Service) Matchers.anyMap(org.mockito.Matchers.anyMap) URLEncodedUtils(org.apache.http.client.utils.URLEncodedUtils) Modifier(java.lang.reflect.Modifier) PowerMockito.doAnswer(org.powermock.api.mockito.PowerMockito.doAnswer) Optional(java.util.Optional) OIDCProcessor(org.wso2.carbon.identity.discovery.OIDCProcessor) NameValuePair(org.apache.http.NameValuePair) FrameworkUtils(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils) MemberMatcher.method(org.powermock.api.support.membermodification.MemberMatcher.method) DefaultOIDCProviderRequestBuilder(org.wso2.carbon.identity.discovery.builders.DefaultOIDCProviderRequestBuilder) OAuth2ScopeService(org.wso2.carbon.identity.oauth2.OAuth2ScopeService) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) DataProvider(org.testng.annotations.DataProvider) PowerMockito.mockStatic(org.powermock.api.mockito.PowerMockito.mockStatic) Mock(org.mockito.Mock) Assert.assertEquals(org.testng.Assert.assertEquals) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) HashMap(java.util.HashMap) Constructor(java.lang.reflect.Constructor) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) BeforeTest(org.testng.annotations.BeforeTest) HttpServletRequest(javax.servlet.http.HttpServletRequest) Assert(org.testng.Assert) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) Base64Utils(org.apache.axiom.util.base64.Base64Utils) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) LoggerUtils(org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils) MultitenantConstants(org.wso2.carbon.base.MultitenantConstants) SessionDataCache(org.wso2.carbon.identity.oauth.cache.SessionDataCache) WebFingerProcessor(org.wso2.carbon.identity.webfinger.WebFingerProcessor) PowerMockito(org.powermock.api.mockito.PowerMockito) SSOConsentService(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.SSOConsentService) IdentityTenantUtil(org.wso2.carbon.identity.core.util.IdentityTenantUtil) WithCarbonHome(org.wso2.carbon.identity.common.testng.WithCarbonHome) PowerMockito.when(org.powermock.api.mockito.PowerMockito.when) HttpServletResponse(javax.servlet.http.HttpServletResponse) Field(java.lang.reflect.Field) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ServerConfiguration(org.wso2.carbon.base.ServerConfiguration) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) OAuth2TokenValidationService(org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest) URLEncoder(java.net.URLEncoder) FileBasedConfigurationBuilder(org.wso2.carbon.identity.application.authentication.framework.config.builder.FileBasedConfigurationBuilder) DefaultWebFingerProcessor(org.wso2.carbon.identity.webfinger.DefaultWebFingerProcessor) PowerMockito.spy(org.powermock.api.mockito.PowerMockito.spy) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OIDCProviderRequestBuilder(org.wso2.carbon.identity.discovery.builders.OIDCProviderRequestBuilder) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) RequestObjectService(org.wso2.carbon.identity.openidconnect.RequestObjectService) IdentityUtil(org.wso2.carbon.identity.core.util.IdentityUtil) Assert.assertTrue(org.testng.Assert.assertTrue) Log(org.apache.commons.logging.Log) ArrayUtils(org.apache.commons.lang.ArrayUtils) NameValuePair(org.apache.http.NameValuePair) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 48 with OAuth2Parameters

use of org.wso2.carbon.identity.oauth2.model.OAuth2Parameters in project identity-inbound-auth-oauth by wso2-extensions.

the class EndpointUtilTest method provideDataForUserConsentURL.

@DataProvider(name = "provideDataForUserConsentURL")
public Object[][] provideDataForUserConsentURL() {
    OAuth2Parameters params = new OAuth2Parameters();
    params.setApplicationName("TestApplication");
    params.setClientId("testClientId");
    params.setScopes(new HashSet<String>(Arrays.asList("scope1", "scope2", "internal_login", "SYSTEM")));
    return new Object[][] { { params, true, true, false, "QueryString", true }, { null, true, true, false, "QueryString", true }, { params, false, true, false, "QueryString", true }, { params, true, false, false, "QueryString", true }, { params, true, false, false, "QueryString", false }, { params, true, true, false, null, true }, { params, true, true, true, "QueryString", true } };
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) Matchers.anyString(org.mockito.Matchers.anyString) DataProvider(org.testng.annotations.DataProvider)

Example 49 with OAuth2Parameters

use of org.wso2.carbon.identity.oauth2.model.OAuth2Parameters in project identity-inbound-auth-oauth by wso2-extensions.

the class EndpointUtilTest method testGetErrorPageURL.

@Test(dataProvider = "provideErrorPageData")
public void testGetErrorPageURL(boolean isImplicitResponse, boolean isHybridResponse, boolean isRedirectToRedirectURI, Object oAuth2ParamObject, String expected, boolean isDebugOn) throws Exception {
    setMockedLog(isDebugOn);
    OAuth2Parameters parameters = (OAuth2Parameters) oAuth2ParamObject;
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(mockedOAuthServerConfiguration);
    when(mockedOAuthServerConfiguration.isRedirectToRequestedRedirectUriEnabled()).thenReturn(isRedirectToRedirectURI);
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.isImplicitResponseType(anyString())).thenReturn(isImplicitResponse);
    when(OAuth2Util.isHybridResponseType(anyString())).thenReturn(isHybridResponse);
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    when(mockedOAuthResponse.getLocationUri()).thenReturn("http://localhost:8080/location");
    when(mockedHttpServletRequest.getParameter(anyString())).thenReturn("http://localhost:8080/location");
    String url = EndpointUtil.getErrorPageURL(mockedHttpServletRequest, "invalid request", "invalid request object", "invalid request", "test", parameters);
    Assert.assertTrue(url.contains(expected), "Expected error redirect url not returned");
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 50 with OAuth2Parameters

use of org.wso2.carbon.identity.oauth2.model.OAuth2Parameters 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)

Aggregations

OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)40 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)23 HashMap (java.util.HashMap)22 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)19 Test (org.testng.annotations.Test)19 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)17 Matchers.anyString (org.mockito.Matchers.anyString)14 BeforeTest (org.testng.annotations.BeforeTest)13 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)13 RequestObjectException (org.wso2.carbon.identity.oauth2.RequestObjectException)12 JSONObject (org.json.JSONObject)10 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)9 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)8 ArrayList (java.util.ArrayList)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)7 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)7 SessionDataCacheKey (org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey)7 OAuth2ScopeConsentResponse (org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse)7 URI (java.net.URI)6