Search in sources :

Example 36 with SessionContext

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()]));
    }
}
Also used : ArrayList(java.util.ArrayList) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)

Example 37 with SessionContext

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");
            }
        }
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ExternalClaim(org.wso2.carbon.identity.claim.metadata.mgt.model.ExternalClaim) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashSet(java.util.HashSet) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 38 with SessionContext

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);
}
Also used : ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) AuthorizationGrantCacheEntry(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext) RequestedClaim(org.wso2.carbon.identity.openidconnect.model.RequestedClaim) Claim(org.wso2.carbon.identity.application.common.model.Claim) ExternalClaim(org.wso2.carbon.identity.claim.metadata.mgt.model.ExternalClaim)

Example 39 with SessionContext

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.");
            }
        }
    }
}
Also used : Event(org.wso2.carbon.identity.event.event.Event) AuthenticationDataPublisher(org.wso2.carbon.identity.application.authentication.framework.AuthenticationDataPublisher)

Example 40 with SessionContext

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));
}
Also used : SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) ExternalIdPConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ExternalIdPConfig) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Aggregations

SessionContext (org.wso2.carbon.identity.application.authentication.framework.context.SessionContext)25 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)14 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 Test (org.testng.annotations.Test)7 SessionContextCacheKey (org.wso2.carbon.identity.application.authentication.framework.cache.SessionContextCacheKey)7 HashMap (java.util.HashMap)6 BeforeTest (org.testng.annotations.BeforeTest)6 SessionContextCacheEntry (org.wso2.carbon.identity.application.authentication.framework.cache.SessionContextCacheEntry)6 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)6 Event (org.wso2.carbon.identity.event.event.Event)6 JSONObject (org.json.JSONObject)5 AuthenticationDataPublisher (org.wso2.carbon.identity.application.authentication.framework.AuthenticationDataPublisher)4 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)4 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)4 ArrayList (java.util.ArrayList)3 Cookie (javax.servlet.http.Cookie)3 AuthHistory (org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)3 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)3 Map (java.util.Map)2 AfterTest (org.testng.annotations.AfterTest)2