use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult 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));
}
}
}
use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method setAuthenticationResult.
private AuthenticationResult setAuthenticationResult(boolean isAuthenticated, Map<ClaimMapping, String> attributes, String errorCode, String errorMsg, String errorUri) {
AuthenticationResult authResult = new AuthenticationResult();
authResult.setAuthenticated(isAuthenticated);
if (!isAuthenticated) {
authResult.addProperty(FrameworkConstants.AUTH_ERROR_CODE, errorCode);
authResult.addProperty(FrameworkConstants.AUTH_ERROR_MSG, errorMsg);
authResult.addProperty(FrameworkConstants.AUTH_ERROR_URI, errorUri);
}
AuthenticatedUser subject = new AuthenticatedUser();
subject.setAuthenticatedSubjectIdentifier(USERNAME);
subject.setUserName(USERNAME);
subject.setUserAttributes(attributes);
subject.setUserId(USER_ID);
authResult.setSubject(subject);
return authResult;
}
use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult 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");
}
}
use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult 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");
}
}
use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method handleSuccessfulAuthentication.
private Response handleSuccessfulAuthentication(OAuthMessage oAuthMessage, OAuth2Parameters oauth2Params, AuthenticationResult authenticationResult) throws OAuthSystemException, URISyntaxException, ConsentHandlingFailedException {
boolean isOIDCRequest = OAuth2Util.isOIDCAuthzRequest(oauth2Params.getScopes());
AuthenticatedUser authenticatedUser = authenticationResult.getSubject();
if (authenticatedUser.getUserAttributes() != null) {
authenticatedUser.setUserAttributes(new ConcurrentHashMap<>(authenticatedUser.getUserAttributes()));
}
addToAuthenticationResultDetailsToOAuthMessage(oAuthMessage, authenticationResult, authenticatedUser);
OIDCSessionState sessionState = new OIDCSessionState();
String redirectURL = null;
try {
redirectURL = doUserAuthorization(oAuthMessage, oAuthMessage.getSessionDataKeyFromLogin(), sessionState);
} catch (OAuthProblemException ex) {
if (StringUtils.equals(oauth2Params.getResponseMode(), RESPONSE_MODE_FORM_POST)) {
return handleFailedState(oAuthMessage, oauth2Params, ex);
} else {
redirectURL = EndpointUtil.getErrorRedirectURL(ex, oauth2Params);
}
}
if (isFormPostResponseMode(oAuthMessage, redirectURL)) {
return handleFormPostMode(oAuthMessage, oauth2Params, redirectURL, isOIDCRequest, sessionState);
}
if (isOIDCRequest) {
redirectURL = manageOIDCSessionState(oAuthMessage, sessionState, oauth2Params, authenticatedUser.getAuthenticatedSubjectIdentifier(), redirectURL, oAuthMessage.getSessionDataCacheEntry());
}
return Response.status(HttpServletResponse.SC_FOUND).location(new URI(redirectURL)).build();
}
Aggregations