use of org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method testHandleOAuthAuthorizationRequest1.
@Test(dataProvider = "provideHandleOAuthAuthorizationRequest1Data", groups = "testWithConnection")
public void testHandleOAuthAuthorizationRequest1(boolean showDisplayName, Object spObj, String savedDisplayName) throws Exception {
ServiceProvider sp = (ServiceProvider) spObj;
sp.setApplicationName(APP_NAME);
mockApplicationManagementService(sp);
mockOAuthServerConfiguration();
mockEndpointUtil(false);
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
mockStatic(LoggerUtils.class);
when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
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(IdentityDatabaseUtil.class);
when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
Map<String, String[]> requestParams = new HashMap();
Map<String, Object> requestAttributes = new HashMap();
requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
requestParams.put(OAuth.OAUTH_RESPONSE_TYPE, new String[] { ResponseType.TOKEN.toString() });
mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
validationResponseDTO.setValidClient(true);
validationResponseDTO.setCallbackURL(APP_REDIRECT_URL);
when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(validationResponseDTO);
Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> responseTypeValidators = new Hashtable<>();
responseTypeValidators.put(ResponseType.CODE.toString(), CodeValidator.class);
responseTypeValidators.put(ResponseType.TOKEN.toString(), TokenValidator.class);
when(oAuthServerConfiguration.getSupportedResponseTypeValidators()).thenReturn(responseTypeValidators);
when(oAuthServerConfiguration.isShowDisplayNameInConsentPage()).thenReturn(showDisplayName);
Method handleOAuthAuthorizationRequest = authzEndpointObject.getClass().getDeclaredMethod("handleOAuthAuthorizationRequest", OAuthMessage.class);
handleOAuthAuthorizationRequest.setAccessible(true);
SessionDataCache sessionDataCache = mock(SessionDataCache.class);
mockStatic(SessionDataCache.class);
when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
final SessionDataCacheEntry[] cacheEntry = new SessionDataCacheEntry[1];
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) {
cacheEntry[0] = (SessionDataCacheEntry) invocation.getArguments()[1];
return null;
}
}).when(sessionDataCache).addToCache(any(SessionDataCacheKey.class), any(SessionDataCacheEntry.class));
when(oAuthMessage.getRequest()).thenReturn(httpServletRequest);
when(oAuthMessage.getClientId()).thenReturn(CLIENT_ID_VALUE);
handleOAuthAuthorizationRequest.invoke(authzEndpointObject, oAuthMessage);
assertNotNull(cacheEntry[0], "Parameters not saved in cache");
assertEquals(cacheEntry[0].getoAuth2Parameters().getDisplayName(), savedDisplayName);
}
use of org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry 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;
}
use of org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method buildAuthRequest.
private OAuth2AuthorizeReqDTO buildAuthRequest(OAuth2Parameters oauth2Params, SessionDataCacheEntry sessionDataCacheEntry, HttpRequestHeaderHandler httpRequestHeaderHandler) {
OAuth2AuthorizeReqDTO authzReqDTO = new OAuth2AuthorizeReqDTO();
authzReqDTO.setCallbackUrl(oauth2Params.getRedirectURI());
authzReqDTO.setConsumerKey(oauth2Params.getClientId());
authzReqDTO.setResponseType(oauth2Params.getResponseType());
authzReqDTO.setScopes(oauth2Params.getScopes().toArray(new String[oauth2Params.getScopes().size()]));
authzReqDTO.setUser(sessionDataCacheEntry.getLoggedInUser());
authzReqDTO.setACRValues(oauth2Params.getACRValues());
authzReqDTO.setNonce(oauth2Params.getNonce());
authzReqDTO.setPkceCodeChallenge(oauth2Params.getPkceCodeChallenge());
authzReqDTO.setPkceCodeChallengeMethod(oauth2Params.getPkceCodeChallengeMethod());
authzReqDTO.setTenantDomain(oauth2Params.getTenantDomain());
authzReqDTO.setAuthTime(sessionDataCacheEntry.getAuthTime());
authzReqDTO.setMaxAge(oauth2Params.getMaxAge());
authzReqDTO.setEssentialClaims(oauth2Params.getEssentialClaims());
authzReqDTO.setSessionDataKey(oauth2Params.getSessionDataKey());
authzReqDTO.setRequestObjectFlow(oauth2Params.isRequestObjectFlow());
authzReqDTO.setIdpSessionIdentifier(sessionDataCacheEntry.getSessionContextIdentifier());
authzReqDTO.setLoggedInTenantDomain(oauth2Params.getLoginTenantDomain());
if (sessionDataCacheEntry.getParamMap() != null && sessionDataCacheEntry.getParamMap().get(OAuthConstants.AMR) != null) {
authzReqDTO.addProperty(OAuthConstants.AMR, sessionDataCacheEntry.getParamMap().get(OAuthConstants.AMR));
}
// Set Selected acr value.
String[] sessionIds = sessionDataCacheEntry.getParamMap().get(FrameworkConstants.SESSION_DATA_KEY);
if (ArrayUtils.isNotEmpty(sessionIds)) {
String commonAuthSessionId = sessionIds[0];
SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(commonAuthSessionId, oauth2Params.getLoginTenantDomain());
if (sessionContext != null && sessionContext.getSessionAuthHistory() != null) {
authzReqDTO.setSelectedAcr(sessionContext.getSessionAuthHistory().getSelectedAcrValue());
}
}
// Adding Httprequest headers and cookies in AuthzDTO.
authzReqDTO.setHttpRequestHeaders(httpRequestHeaderHandler.getHttpRequestHeaders());
authzReqDTO.setCookie(httpRequestHeaderHandler.getCookies());
return authzReqDTO;
}
use of org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method associateAuthenticationHistory.
/**
* Associates the authentication method references done while logged into the session (if any) to the OAuth cache.
* The SessionDataCacheEntry then will be used when getting "AuthenticationMethodReferences". Please see
* <a href="https://tools.ietf.org/html/draft-ietf-oauth-amr-values-02" >draft-ietf-oauth-amr-values-02</a>.
*
* @param resultFromLogin
* @param cookie
*/
private void associateAuthenticationHistory(SessionDataCacheEntry resultFromLogin, Cookie cookie) {
SessionContext sessionContext = getSessionContext(cookie, resultFromLogin.getoAuth2Parameters().getLoginTenantDomain());
if (sessionContext != null && sessionContext.getSessionAuthHistory() != null && sessionContext.getSessionAuthHistory().getHistory() != null) {
List<String> authMethods = new ArrayList<>();
for (AuthHistory authHistory : sessionContext.getSessionAuthHistory().getHistory()) {
authMethods.add(authHistory.toTranslatableString());
}
resultFromLogin.getParamMap().put(OAuthConstants.AMR, authMethods.toArray(new String[authMethods.size()]));
}
}
use of org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry 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);
}
Aggregations