use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext 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.application.authentication.framework.context.SessionContext in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method testUserConsentResponse.
@Test(dataProvider = "provideConsentData", groups = "testWithConnection")
public void testUserConsentResponse(String consent, String redirectUrl, Set<String> scopes, int expectedStatus, String oAuthErrorDTODescription, String expectedError) throws Exception {
initMocks(this);
spy(FrameworkUtils.class);
when(authCookie.getValue()).thenReturn("dummyValue");
doReturn(authCookie).when(FrameworkUtils.class, "getAuthCookie", any());
doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
doNothing().when(FrameworkUtils.class, "endTenantFlow");
mockStatic(LoggerUtils.class);
when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
SessionContext sessionContext = new SessionContext();
sessionContext.addProperty(FrameworkConstants.CREATED_TIMESTAMP, 1479249799770L);
doReturn(sessionContext).when(FrameworkUtils.class, "getSessionContextFromCache", anyString(), anyString());
when(openIDConnectClaimFilter.getClaimsFilteredByOIDCScopes(any(), anyString())).thenReturn(Arrays.asList("country"));
OAuth2AuthzEndpoint.setOpenIDConnectClaimFilter(openIDConnectClaimFilter);
Set<ExternalClaim> mappings = new HashSet<>();
ExternalClaim claim = new ExternalClaim(OIDC_DIALECT, "country", "http://wso2.org/country");
mappings.add(claim);
when(claimMetadataHandler.getMappingsFromOtherDialectToCarbon(anyString(), any(), anyString())).thenReturn(mappings);
mockStatic(ClaimMetadataHandler.class);
when(ClaimMetadataHandler.getInstance()).thenReturn(claimMetadataHandler);
mockStatic(SessionDataCache.class);
when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
SessionDataCacheKey consentDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_CONSENT_VALUE);
when(sessionDataCache.getValueFromCache(consentDataCacheKey)).thenReturn(consentCacheEntry);
Map<String, String[]> requestParams = new HashMap<>();
Map<String, Object> requestAttributes = new ConcurrentHashMap<>();
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);
OAuth2Parameters oAuth2Params = setOAuth2Parameters(scopes, APP_NAME, RESPONSE_MODE_FORM_POST, redirectUrl);
oAuth2Params.setClientId(CLIENT_ID_VALUE);
when(consentCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
when(consentCacheEntry.getLoggedInUser()).thenReturn(new AuthenticatedUser());
mockStatic(OpenIDConnectUserRPStore.class);
when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
doNothing().when(openIDConnectUserRPStore).putUserRPToStore(any(AuthenticatedUser.class), anyString(), anyBoolean(), anyString());
mockOAuthServerConfiguration();
mockStatic(OAuth2Util.OAuthURL.class);
when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
spy(OAuth2Util.class);
doReturn(new ServiceProvider()).when(OAuth2Util.class, "getServiceProvider", CLIENT_ID_VALUE);
mockEndpointUtil(true);
when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
mockApplicationManagementService();
when(oAuth2Service.handleUserConsentDenial(oAuth2Params)).thenReturn(oAuthErrorDTO);
when(oAuthErrorDTO.getErrorDescription()).thenReturn(oAuthErrorDTODescription);
Response response;
try {
response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
} catch (InvalidRequestParentException ire) {
InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
response = invalidRequestExceptionMapper.toResponse(ire);
}
if (response != null) {
assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
assertNotNull(responseMetadata);
if (expectedError != null) {
if (response.getEntity() != null) {
String htmlPost = response.getEntity().toString();
assertTrue(htmlPost.contains(expectedError));
} else {
CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION));
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(expectedError), "Expected error code not found in URL");
}
}
}
}
use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method addUserAttributesToOAuthMessage.
private void addUserAttributesToOAuthMessage(OAuthMessage oAuthMessage, String code, String codeId, String tokenBindingValue) throws OAuthSystemException {
SessionDataCacheEntry sessionDataCacheEntry = oAuthMessage.getSessionDataCacheEntry();
AuthorizationGrantCacheEntry authorizationGrantCacheEntry = new AuthorizationGrantCacheEntry(sessionDataCacheEntry.getLoggedInUser().getUserAttributes());
ClaimMapping key = new ClaimMapping();
Claim claimOfKey = new Claim();
claimOfKey.setClaimUri(OAuth2Util.SUB);
key.setRemoteClaim(claimOfKey);
String sub = sessionDataCacheEntry.getLoggedInUser().getUserAttributes().get(key);
if (StringUtils.isBlank(sub)) {
sub = sessionDataCacheEntry.getLoggedInUser().getAuthenticatedSubjectIdentifier();
}
if (StringUtils.isNotBlank(sub)) {
if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
log.debug("Setting subject: " + sub + " as the sub claim in cache against the authorization code.");
}
authorizationGrantCacheEntry.setSubjectClaim(sub);
}
// PKCE
String[] pkceCodeChallengeArray = sessionDataCacheEntry.getParamMap().get(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE);
String[] pkceCodeChallengeMethodArray = sessionDataCacheEntry.getParamMap().get(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE_METHOD);
String pkceCodeChallenge = null;
String pkceCodeChallengeMethod = null;
if (ArrayUtils.isNotEmpty(pkceCodeChallengeArray)) {
pkceCodeChallenge = pkceCodeChallengeArray[0];
}
if (ArrayUtils.isNotEmpty(pkceCodeChallengeMethodArray)) {
pkceCodeChallengeMethod = pkceCodeChallengeMethodArray[0];
}
authorizationGrantCacheEntry.setAcrValue(sessionDataCacheEntry.getoAuth2Parameters().getACRValues());
authorizationGrantCacheEntry.setNonceValue(sessionDataCacheEntry.getoAuth2Parameters().getNonce());
authorizationGrantCacheEntry.setCodeId(codeId);
authorizationGrantCacheEntry.setPkceCodeChallenge(pkceCodeChallenge);
authorizationGrantCacheEntry.setPkceCodeChallengeMethod(pkceCodeChallengeMethod);
authorizationGrantCacheEntry.setEssentialClaims(sessionDataCacheEntry.getoAuth2Parameters().getEssentialClaims());
authorizationGrantCacheEntry.setAuthTime(sessionDataCacheEntry.getAuthTime());
authorizationGrantCacheEntry.setMaxAge(sessionDataCacheEntry.getoAuth2Parameters().getMaxAge());
authorizationGrantCacheEntry.setTokenBindingValue(tokenBindingValue);
authorizationGrantCacheEntry.setSessionContextIdentifier(sessionDataCacheEntry.getSessionContextIdentifier());
String[] sessionIds = sessionDataCacheEntry.getParamMap().get(FrameworkConstants.SESSION_DATA_KEY);
if (ArrayUtils.isNotEmpty(sessionIds)) {
String commonAuthSessionId = sessionIds[0];
SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(commonAuthSessionId, sessionDataCacheEntry.getoAuth2Parameters().getLoginTenantDomain());
if (sessionContext != null) {
String selectedAcr = sessionContext.getSessionAuthHistory().getSelectedAcrValue();
authorizationGrantCacheEntry.setSelectedAcrValue(selectedAcr);
}
}
String[] amrEntries = sessionDataCacheEntry.getParamMap().get(OAuthConstants.AMR);
if (amrEntries != null) {
for (String amrEntry : amrEntries) {
authorizationGrantCacheEntry.addAmr(amrEntry);
}
}
authorizationGrantCacheEntry.setAuthorizationCode(code);
boolean isRequestObjectFlow = sessionDataCacheEntry.getoAuth2Parameters().isRequestObjectFlow();
authorizationGrantCacheEntry.setRequestObjectFlow(isRequestObjectFlow);
oAuthMessage.setAuthorizationGrantCacheEntry(authorizationGrantCacheEntry);
}
use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project identity-data-publisher-authentication by wso2-extensions.
the class AuthnDataPublisherProxy method publishSessionCreation.
/**
* Publishes session creation information after managing handler operations
*
* @param request Incoming request for authentication
* @param context Authentication Context
* @param sessionContext Session context
* @param unmodifiableMap Other relevant parameters which needs to be published
*/
public void publishSessionCreation(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> unmodifiableMap) {
Event event = createEvent(request, context, sessionContext, unmodifiableMap, EventName.SESSION_CREATE);
doPublishEvent(event);
for (AuthenticationDataPublisher publisher : dataPublishers) {
if (isPublisherEnabledAndCanHandle(context, publisher)) {
publisher.publishSessionCreation(request, context, sessionContext, unmodifiableMap);
if (log.isDebugEnabled()) {
log.debug(publisher.getName() + " is invoked.");
}
}
}
}
use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project identity-data-publisher-authentication by wso2-extensions.
the class AuthenticationAuditLogger method publishSessionTermination.
public void publishSessionTermination(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> unmodifiableMap) {
if (context == null) {
return;
}
SequenceConfig sequenceConfig = context.getSequenceConfig();
AuthenticatedUser authenticatedUser = null;
String username = "";
String tenantDomain = "";
String authenticatedIDPs = "";
if (sequenceConfig != null && sequenceConfig.getAuthenticatedUser() != null) {
authenticatedUser = sequenceConfig.getAuthenticatedUser();
authenticatedIDPs = sequenceConfig.getAuthenticatedIdPs();
} else {
Object authenticatedUserObj = sessionContext.getProperty(FrameworkConstants.AUTHENTICATED_USER);
if (authenticatedUserObj != null) {
authenticatedUser = (AuthenticatedUser) authenticatedUserObj;
}
}
if (authenticatedUser != null) {
username = authenticatedUser.getAuthenticatedSubjectIdentifier();
tenantDomain = authenticatedUser.getTenantDomain();
}
String auditData = "\"" + "ContextIdentifier" + "\" : \"" + context.getContextIdentifier() + "\",\"" + "LoggedOutUser" + "\" : \"" + username + "\",\"" + "LoggedOutUserTenantDomain" + "\" : \"" + tenantDomain + "\",\"" + "ServiceProviderName" + "\" : \"" + context.getServiceProviderName() + "\",\"" + "RequestType" + "\" : \"" + context.getRequestType() + "\",\"" + "RelyingParty" + "\" : \"" + context.getRelyingParty() + "\",\"" + "AuthenticatedIdPs" + "\" : \"" + authenticatedIDPs + "\"";
String idpName = null;
ExternalIdPConfig externalIdPConfig = context.getExternalIdP();
if (externalIdPConfig != null) {
idpName = externalIdPConfig.getName();
}
AUDIT_LOG.info(String.format(FrameworkConstants.AUDIT_MESSAGE, username, "Logout", idpName, auditData, FrameworkConstants.AUDIT_SUCCESS));
}
Aggregations