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");
}
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"));
}
}
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 } };
}
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");
}
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");
}
}
Aggregations