use of org.wso2.carbon.identity.oauth.cache.SessionDataCache in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuthRequestStateValidator method validateRequest.
private void validateRequest(OAuthMessage oAuthMessage) throws InvalidRequestParentException {
validateRepeatedParameters(oAuthMessage);
if (oAuthMessage.getResultFromLogin() != null && oAuthMessage.getResultFromConsent() != null) {
if (log.isDebugEnabled()) {
log.debug("Invalid authorization request.\'SessionDataKey\' found in request as parameter and " + "attribute, and both have non NULL objects in cache");
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "invalid 'SessionDataKey' parameter in authorization request", "validate-input-parameters", null);
}
throw new InvalidRequestException("Invalid authorization request", OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_AUTHORIZATION_REQUEST);
} else if (oAuthMessage.getClientId() == null && oAuthMessage.getResultFromLogin() == null && oAuthMessage.getResultFromConsent() == null) {
if (log.isDebugEnabled()) {
log.debug("Invalid authorization request.\'SessionDataKey\' not found in request as parameter or " + "attribute, and client_id parameter cannot be found in request");
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "invalid 'client_id' and 'SessionDataKey' parameters cannot be found in request", "validate-input-parameters", null);
}
throw new InvalidRequestException("Invalid authorization request", OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_CLIENT);
} else if (oAuthMessage.getSessionDataKeyFromLogin() != null && oAuthMessage.getResultFromLogin() == null) {
if (log.isDebugEnabled()) {
log.debug("Session data not found in SessionDataCache for " + oAuthMessage.getSessionDataKeyFromLogin());
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Access denied since user session has timed-out.", "validate-input-parameters", null);
}
throw new AccessDeniedException("Session Timed Out", OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ErrorCodes.OAuth2SubErrorCodes.SESSION_TIME_OUT);
} else if (oAuthMessage.getSessionDataKeyFromConsent() != null && oAuthMessage.getResultFromConsent() == null) {
if (oAuthMessage.getResultFromLogin() == null) {
if (log.isDebugEnabled()) {
log.debug("Session data not found in SessionDataCache for " + oAuthMessage.getSessionDataKeyFromConsent());
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Access denied since user session has timed-out.", "validate-input-parameters", null);
}
throw new AccessDeniedException("Session Timed Out", OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ErrorCodes.OAuth2SubErrorCodes.SESSION_TIME_OUT);
} else {
// if the sessionDataKeyFromConsent parameter present in the login request, skip it and allow login
// since result from login is there.
oAuthMessage.setSessionDataKeyFromConsent(null);
}
}
}
use of org.wso2.carbon.identity.oauth.cache.SessionDataCache 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.oauth.cache.SessionDataCache 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");
}
}
}
use of org.wso2.carbon.identity.oauth.cache.SessionDataCache 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");
}
}
Aggregations