org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext Java Examples

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultStepBasedSequenceHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private AuthenticationContext getMockedContextForJitProvisioning(String provisioningUserStoreId,
                                                                 String provisioningUserStoreClaimUri,
                                                                 String tenantDomain) {

    ExternalIdPConfig externalIdPConfig = spy(new ExternalIdPConfig());
    when(externalIdPConfig.getProvisioningUserStoreId()).thenReturn(provisioningUserStoreId);
    when(externalIdPConfig.getProvisioningUserStoreClaimURI()).thenReturn(provisioningUserStoreClaimUri);

    ApplicationConfig applicationConfig = new ApplicationConfig(new ServiceProvider());
    applicationConfig.setApplicationName("DUMMY_NAME");

    SequenceConfig sequenceConfig = new SequenceConfig();
    sequenceConfig.setApplicationConfig(applicationConfig);

    context.setTenantDomain(tenantDomain);
    context.setSequenceConfig(sequenceConfig);
    context.setExternalIdP(externalIdPConfig);

    return context;
}
 
Example #2
Source File: FrameworkUtils.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param contextId
 * @return
 */
public static AuthenticationContext getAuthenticationContextFromCache(String contextId) {

    AuthenticationContext authenticationContext = null;
    AuthenticationContextCacheKey cacheKey = new AuthenticationContextCacheKey(contextId);
    AuthenticationContextCacheEntry authenticationContextCacheEntry = AuthenticationContextCache.getInstance().
            getValueFromCache(cacheKey);

    if (authenticationContextCacheEntry != null) {
        authenticationContext = authenticationContextCacheEntry.getContext();
    }

    if (log.isDebugEnabled() && authenticationContext == null) {
        log.debug("Authentication Context is null");
    }

    return authenticationContext;
}
 
Example #3
Source File: JsAuthenticationContextTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoteAddition() throws ScriptException {

    AuthenticatedUser authenticatedUser = new AuthenticatedUser();
    AuthenticationContext authenticationContext = new AuthenticationContext();
    setupAuthContextWithStepData(authenticationContext, authenticatedUser);

    JsAuthenticationContext jsAuthenticationContext = new JsAuthenticationContext(authenticationContext);
    Bindings bindings = scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE);
    bindings.put("context", jsAuthenticationContext);

    scriptEngine.eval("context.steps[1].subject.remoteClaims['testClaim']='testValue'");

    ClaimMapping claimMapping = ClaimMapping.build("testClaim", "testClaim", "", false);
    String claimCreatedByJs = authenticatedUser.getUserAttributes().get(claimMapping);
    assertEquals(claimCreatedByJs, "testValue");
}
 
Example #4
Source File: DefaultClaimHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Set federated subject's SP Subject Claim URI as a property
 */
private void setSubjectClaimForFederatedClaims(Map<String, String> attributesMap,
                                               String spStandardDialect,
                                               AuthenticationContext context) {

    String subjectURI = context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri();
    if (subjectURI != null && !subjectURI.isEmpty()) {
        if (spStandardDialect != null) {
            setSubjectClaim(null, null, attributesMap, spStandardDialect, context);
            if (context.getProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE) == null) {
                log.warn("Subject claim could not be found amongst locally mapped " +
                         "unfiltered remote claims");
            }
        } else {
            setSubjectClaim(null, null, attributesMap, null, context);
            if (context.getProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE) == null) {
                log.warn("Subject claim could not be found amongst service provider mapped " +
                         "unfiltered remote claims");
            }
        }
    }
}
 
Example #5
Source File: DefaultClaimHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Set federated subject's SP Subject Claim URI as a property
 */
private void setSubjectClaimForLocalClaims(String tenantAwareUserId,
                                           UserStoreManager userStore,
                                           Map<String, String> attributesMap,
                                           String spStandardDialect,
                                           AuthenticationContext context) {

    String subjectURI = context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri();
    if (subjectURI != null && !subjectURI.isEmpty()) {
        if (spStandardDialect != null) {
            setSubjectClaim(tenantAwareUserId, userStore, attributesMap, spStandardDialect, context);
            if (context.getProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE) == null) {
                log.warn("Subject claim could not be found amongst unfiltered local claims");
            }
        } else {
            setSubjectClaim(tenantAwareUserId, userStore, attributesMap, null, context);
            if (context.getProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE) == null) {
                log.warn("Subject claim could not be found amongst service provider mapped " +
                         "unfiltered local claims");
            }
        }
    }
}
 
Example #6
Source File: GraphBasedSequenceHandlerNoJsTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "noJsDataProvider")
public void testHandleStaticSequence(String spFileName, int authHistoryCount) throws
        Exception {
    ServiceProvider sp1 = getTestServiceProvider(spFileName);

    AuthenticationContext context = getAuthenticationContext(sp1);

    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.<String, String[]>emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);

    HttpServletRequest req = mock(HttpServletRequest.class);

    HttpServletResponse resp = mock(HttpServletResponse.class);

    UserCoreUtil.setDomainInThreadLocal("test_domain");

    graphBasedSequenceHandler.handle(req, resp, context);

    List<AuthHistory> authHistories = context.getAuthenticationStepHistory();
    assertNotNull(authHistories);
    assertEquals(authHistories.size(), authHistoryCount);
}
 
Example #7
Source File: DefaultAuthenticationRequestHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private AuthenticationResult getAuthenticationResult(HttpServletRequest request,
                                                     HttpServletResponse response,
                                                     AuthenticationContext context) {

    AuthenticationResult authenticationResult = null;
    if (FrameworkUtils.getCacheDisabledAuthenticators().contains(context.getRequestType())
            && (response instanceof CommonAuthResponseWrapper) &&
            !((CommonAuthResponseWrapper) response).isWrappedByFramework()) {
        // Get the authentication result from the request
        authenticationResult =
                (AuthenticationResult) request.getAttribute(FrameworkConstants.RequestAttribute.AUTH_RESULT);
    } else {
        // Retrieve the authentication result from cache
        AuthenticationResultCacheEntry authenticationResultCacheEntry =
                FrameworkUtils.getAuthenticationResultFromCache(context.getCallerSessionKey());
        if (authenticationResultCacheEntry != null) {
            authenticationResult = authenticationResultCacheEntry.getResult();
        }
    }
    return authenticationResult;
}
 
Example #8
Source File: DefaultStepBasedSequenceHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private StepHandler getMockedStepHandlerForSuccessfulRequestAuthentication() throws Exception {
    // mock the step handler
    StepHandler stepHandler = mock(StepHandler.class);
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            AuthenticationContext context = invocationOnMock.getArgumentAt(2, AuthenticationContext.class);
            StepConfig stepConfig = context.getSequenceConfig().getStepMap().get(context.getCurrentStep());
            stepConfig.setCompleted(true);
            context.setRequestAuthenticated(true);
            return null;
        }
    }).when(stepHandler).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
            any(AuthenticationContext.class));

    return stepHandler;
}
 
Example #9
Source File: DefaultClaimHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void setSubjectClaimForStandardDialect(String tenantAwareUserId, UserStoreManager userStore,
                                               AuthenticationContext context, String subjectURI) {
    try {
        String value = userStore.getUserClaimValue(tenantAwareUserId, subjectURI, null);
        if (value != null) {
            context.setProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE, value);
            if (log.isDebugEnabled()) {
                log.debug("Setting \'ServiceProviderSubjectClaimValue\' property value " +
                          "from user store " + value);
            }
        } else {
            if(log.isDebugEnabled()) {
                log.debug("Subject claim for " + tenantAwareUserId + " not found in user store");
            }
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while retrieving " + subjectURI + " claim value for user " + tenantAwareUserId,
                e);
    }
}
 
Example #10
Source File: DefaultAuthenticationRequestHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "sendResponseDataProvider")
public void testSendResponse(boolean isRequestAuthenticated,
                             boolean isRememberMe,
                             String callerPath,
                             String sessionDataKey,
                             String expectedRedirectUrl) throws Exception {

    AuthenticationContext context = new AuthenticationContext();
    context.setRequestAuthenticated(isRequestAuthenticated);
    context.setRememberMe(isRememberMe);
    context.setCallerPath(callerPath);
    context.setCallerSessionKey(sessionDataKey);

    SequenceConfig sequenceConfig = spy(new SequenceConfig());
    context.setSequenceConfig(sequenceConfig);

    DefaultAuthenticationRequestHandler requestHandler = spy(new DefaultAuthenticationRequestHandler());
    doNothing().when(requestHandler).populateErrorInformation(request, response, context);

    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    requestHandler.sendResponse(request, response, context);
    verify(response).sendRedirect(captor.capture());
    assertEquals(captor.getValue(), expectedRedirectUrl);
}
 
Example #11
Source File: JsAuthenticationContextTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void setupAuthContextWithStepData(AuthenticationContext context, AuthenticatedUser authenticatedUser) {

        SequenceConfig sequenceConfig = new SequenceConfig();
        Map<Integer, StepConfig> stepConfigMap = new HashMap<>();
        StepConfig stepConfig = new StepConfig();
        stepConfig.setOrder(1);
        stepConfig.setAuthenticatedIdP(TEST_IDP);
        stepConfigMap.put(1, stepConfig);
        sequenceConfig.setStepMap(stepConfigMap);
        AuthenticationGraph authenticationGraph = new AuthenticationGraph();
        authenticationGraph.setStepMap(stepConfigMap);
        sequenceConfig.setAuthenticationGraph(authenticationGraph);
        context.setSequenceConfig(sequenceConfig);
        Map<String, AuthenticatedIdPData> idPDataMap = new HashMap<>();
        AuthenticatedIdPData idPData = new AuthenticatedIdPData();
        idPData.setUser(authenticatedUser);
        idPData.setIdpName(TEST_IDP);
        idPDataMap.put(TEST_IDP, idPData);
        context.setCurrentAuthenticatedIdPs(idPDataMap);
    }
 
Example #12
Source File: GraphBasedSequenceHandlerCustomFunctionsTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testHandleDynamicJavascript1() throws Exception {

    JsFunctionRegistryImpl jsFunctionRegistrar = new JsFunctionRegistryImpl();
    FrameworkServiceDataHolder.getInstance().setJsFunctionRegistry(jsFunctionRegistrar);
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "fn1",
            (Function<JsAuthenticationContext, String>) GraphBasedSequenceHandlerCustomFunctionsTest::customFunction1);
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "fn2", new CustomFunctionImpl2());

    AuthenticationContext context = processSequenceWithAcr(new String[] { "acr1" });
    List<AuthHistory> authHistories = context.getAuthenticationStepHistory();
    assertNotNull(authHistories);
    assertEquals(3, authHistories.size());
    assertEquals(authHistories.get(0).getAuthenticatorName(), "BasicMockAuthenticator");
    assertEquals(authHistories.get(1).getAuthenticatorName(), "HwkMockAuthenticator");
    assertEquals(authHistories.get(2).getAuthenticatorName(), "FptMockAuthenticator");
}
 
Example #13
Source File: JITProvisioningPostAuthenticationHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * To add the missing claims.
 *
 * @param uriBuilder Relevant URI builder.
 * @param context    Authentication context.
 */
private void addMissingClaims(URIBuilder uriBuilder, AuthenticationContext context) {

    String[] missingClaims = FrameworkUtils.getMissingClaims(context);
    if (StringUtils.isNotEmpty(missingClaims[1])) {
        if (log.isDebugEnabled()) {
            String username = context.getSequenceConfig().getAuthenticatedUser()
                    .getAuthenticatedSubjectIdentifier();
            String idPName = context.getExternalIdP().getIdPName();
            log.debug("Mandatory claims for SP, " + missingClaims[1] + " is missing for the user : " + username
                    + " from the IDP " + idPName);
        }
        uriBuilder.addParameter(FrameworkConstants.MISSING_CLAIMS, missingClaims[1]);
        uriBuilder.addParameter(FrameworkConstants.MISSING_CLAIMS_DISPLAY_NAME, missingClaims[0]);
    }
}
 
Example #14
Source File: AbstractLocalApplicationAuthenticator.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * To process the logout flow.
 *
 * @param request  the httpServletRequest
 * @param response the httpServletResponse
 * @param context  the authentication context
 * @return the authentication flow status
 * @throws LogoutFailedException the exception in logout flow
 */
protected AuthenticatorFlowStatus processLogoutFlow(HttpServletRequest request, HttpServletResponse response,
                                                    AuthenticationContext context) throws LogoutFailedException {

    try {
        if (!canHandle(request)) {
            context.setCurrentAuthenticator(getName());
            initiateLogoutRequest(request, response, context);
            return AuthenticatorFlowStatus.INCOMPLETE;
        } else {
            processLogoutResponse(request, response, context);
            return AuthenticatorFlowStatus.SUCCESS_COMPLETED;
        }
    } catch (UnsupportedOperationException e) {
        if (log.isDebugEnabled()) {
            log.debug("Ignoring UnsupportedOperationException.", e);
        }
        return AuthenticatorFlowStatus.SUCCESS_COMPLETED;
    }
}
 
Example #15
Source File: PassiveSTSAuthenticator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
protected void processAuthenticationResponse(HttpServletRequest request,
                                             HttpServletResponse response, AuthenticationContext context)
        throws AuthenticationFailedException {

    ExternalIdPConfig externalIdPConfig = context.getExternalIdP();

    if (request.getParameter(PassiveSTSConstants.HTTP_PARAM_PASSIVE_STS_RESULT) != null) {
        try {
            new PassiveSTSManager(externalIdPConfig).processResponse(request, context);
        } catch (PassiveSTSException e) {
            log.error("Exception while processing WS-Federation response", e);
            throw new AuthenticationFailedException(e.getMessage(), e);
        }
    } else {
        log.error("wresult can not be found in request");
        throw new AuthenticationFailedException("wresult can not be found in request");
    }

}
 
Example #16
Source File: DefaultClaimHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Set federated subject's SP Subject Claim URI as a property
 */
private void setSubjectClaimForLocalClaims(String tenantAwareUserId,
                                           UserStoreManager userStore,
                                           Map<String, String> attributesMap,
                                           String spStandardDialect,
                                           AuthenticationContext context) {

    String subjectURI = context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri();
    if (subjectURI != null && !subjectURI.isEmpty()) {
        if (spStandardDialect != null) {
            setSubjectClaim(tenantAwareUserId, userStore, attributesMap, spStandardDialect, context);
            if (context.getProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE) == null) {
                log.warn("Subject claim could not be found amongst unfiltered local claims");
            }
        } else {
            setSubjectClaim(tenantAwareUserId, userStore, attributesMap, null, context);
            if (context.getProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE) == null) {
                log.warn("Subject claim could not be found amongst service provider mapped " +
                         "unfiltered local claims");
            }
        }
    }
}
 
Example #17
Source File: DefaultStepBasedSequenceHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private StepHandler getMockedStepHandlerForIncompleteStep(final boolean isRequestAuthenticated) throws Exception {
    // mock the step handler
    StepHandler stepHandler = mock(StepHandler.class);
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            AuthenticationContext context = invocationOnMock.getArgumentAt(2, AuthenticationContext.class);
            StepConfig stepConfig = context.getSequenceConfig().getStepMap().get(context.getCurrentStep());
            stepConfig.setCompleted(false);
            context.setRequestAuthenticated(isRequestAuthenticated);
            return null;
        }
    }).when(stepHandler).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
            any(AuthenticationContext.class));
    return stepHandler;
}
 
Example #18
Source File: DefaultAuthenticationRequestHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostAuthenticationHandlers() throws Exception {

    Cookie[] cookies = new Cookie[1];
    HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class);
    HttpServletResponse response = PowerMockito.mock(HttpServletResponse.class);
    AuthenticationContext context = prepareContextForPostAuthnTests();
    authenticationRequestHandler.handle(request, response, context);
    assertNull(context.getParameter(FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED));
    String pastrCookie = context.getParameter(FrameworkConstants.PASTR_COOKIE).toString();
    cookies[0] = new Cookie(FrameworkConstants.PASTR_COOKIE + "-" + context.getContextIdentifier(),
            pastrCookie);
    when(request.getCookies()).thenReturn(cookies);
    when(FrameworkUtils.getCookie(any(HttpServletRequest.class), anyString())).thenReturn
            (cookies[0]);
    authenticationRequestHandler.handle(request, response, context);
    assertTrue(Boolean.parseBoolean(context.getProperty(
            FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED).toString()));
}
 
Example #19
Source File: DefaultAuthenticationRequestHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = PostAuthenticationFailedException.class)
public void testPostAuthenticationHandlerFailures() throws Exception {

    Cookie[] cookies = new Cookie[1];
    HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class);
    HttpServletResponse response = PowerMockito.mock(HttpServletResponse.class);
    AuthenticationContext context = prepareContextForPostAuthnTests();
    when(FrameworkUtils.getStepBasedSequenceHandler()).thenReturn(new DefaultStepBasedSequenceHandler());
    authenticationRequestHandler.handle(request, response, context);
    assertNull(context.getParameter(FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED));
    String pastrCookie = context.getParameter(FrameworkConstants.PASTR_COOKIE).toString();
    cookies[0] = new Cookie(FrameworkConstants.PASTR_COOKIE + "-" + context.getContextIdentifier(), pastrCookie);
    when(request.getCookies()).thenReturn(cookies);
    when(FrameworkUtils.getCookie(any(HttpServletRequest.class), anyString())).thenReturn
            (new Cookie(FrameworkConstants.PASTR_COOKIE + "-" + context.getContextIdentifier(),
                    "someGibberishValue"));
    authenticationRequestHandler.handle(request, response, context);
    assertTrue(Boolean.parseBoolean(context.getProperty(
            FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED).toString()));
}
 
Example #20
Source File: FrameworkUtils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static void publishSessionEvent(String sessionId, HttpServletRequest request, AuthenticationContext
        context, SessionContext sessionContext, AuthenticatedUser user, String status) {
    AuthenticationDataPublisher authnDataPublisherProxy = FrameworkServiceDataHolder.getInstance()
            .getAuthnDataPublisherProxy();
    if (authnDataPublisherProxy != null && authnDataPublisherProxy.isEnabled(context)) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(FrameworkConstants.AnalyticsAttributes.USER, user);
        paramMap.put(FrameworkConstants.AnalyticsAttributes.SESSION_ID, sessionId);
        Map<String, Object> unmodifiableParamMap = Collections.unmodifiableMap(paramMap);
        if (FrameworkConstants.AnalyticsAttributes.SESSION_CREATE.equalsIgnoreCase(status)) {
            authnDataPublisherProxy.publishSessionCreation(request, context, sessionContext,
                    unmodifiableParamMap);
        } else if (FrameworkConstants.AnalyticsAttributes.SESSION_UPDATE.equalsIgnoreCase(status)) {
            authnDataPublisherProxy.publishSessionUpdate(request, context, sessionContext,
                    unmodifiableParamMap);
        } else if (FrameworkConstants.AnalyticsAttributes.SESSION_TERMINATE.equalsIgnoreCase(status)) {
            authnDataPublisherProxy.publishSessionTermination(request, context, sessionContext,
                    unmodifiableParamMap);
        }
    }
}
 
Example #21
Source File: DefaultStepHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
protected void handleFailedAuthentication(HttpServletRequest request,
                                          HttpServletResponse response,
                                          AuthenticationContext context,
                                          AuthenticatorConfig authenticatorConfig,
                                          User user) {
    context.setRequestAuthenticated(false);
    request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.FAIL_COMPLETED);
}
 
Example #22
Source File: AbstractLocalApplicationAuthenticator.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * To check whether user domain and tenant domain equal for non SaaS application.
 *
 * @param context the authentication context
 * @throws AuthenticationFailedException the exception in the authentication flow
 */
protected void validateNonSaasAppLogin(AuthenticationContext context) throws AuthenticationFailedException {

    String userTenantDomain = context.getSubject().getTenantDomain();
    String spTenantDomain = context.getTenantDomain();
    if (!StringUtils.equals(userTenantDomain, spTenantDomain)) {
        context.setProperty(FrameworkConstants.USER_TENANT_DOMAIN_MISMATCH, true);
        throw new AuthenticationFailedException("Service Provider tenant domain must be " +
                "equal to user tenant domain for non-SaaS applications", context.getSubject());
    }
}
 
Example #23
Source File: AbstractFrameworkTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
protected AuthenticationContext getAuthenticationContext(ServiceProvider serviceProvider) {
    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setServiceProviderName(serviceProvider.getApplicationName());
    authenticationContext.setTenantDomain("test_domain");
    authenticationContext.setCurrentStep(1);
    authenticationContext.setContextIdentifier(UUID.randomUUID().toString());
    return authenticationContext;
}
 
Example #24
Source File: OpenIDAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
protected void processAuthenticationResponse(HttpServletRequest request,
                                             HttpServletResponse response, AuthenticationContext context)
        throws AuthenticationFailedException {

    OpenIDManager manager = getNewOpenIDManagerInstance();

    try {
        manager.processOpenIDLoginResponse(request, response, context);

        AuthenticatedUser authenticatedSubject = context.getSubject();
        String subject = null;
        String isSubjectInClaimsProp = context.getAuthenticatorProperties().get(
                IdentityApplicationConstants.Authenticator.SAML2SSO.IS_USER_ID_IN_CLAIMS);
        if ("true".equalsIgnoreCase(isSubjectInClaimsProp)) {
            subject = getSubjectFromUserIDClaimURI(context);
        }

        if (subject == null) {
            subject = authenticatedSubject.getAuthenticatedSubjectIdentifier();
        }

        if (subject == null) {
            throw new OpenIDException("Cannot find federated User Identifier");
        }

        authenticatedSubject.setAuthenticatedSubjectIdentifier(subject);

    } catch (OpenIDException e) {
        log.error("Error when processing response from OpenID Provider", e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}
 
Example #25
Source File: DefaultSequenceHandlerUtils.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Get the roles from service provider requested claims.
 * After the service provider claims mappings the role claim URI could
 * change from the local role claim uri. This method will find the
 * roles based on the given role claim URI or the proper role claim URI.
 *
 * @param context        AuthenticationContext.
 * @param sequenceConfig SequenceConfig.
 * @param mappedAttrs    Service Provider mapped claims.
 * @param spRoleUri      Service Provider role claim URiI.
 * @return Roles.
 * @throws FrameworkException
 */
public static String[] getRolesFromSPMappedClaims(AuthenticationContext context, SequenceConfig sequenceConfig,
                                                  Map<String, String> mappedAttrs, String spRoleUri)
        throws FrameworkException {

    String spStandardDialect = DefaultSequenceHandlerUtils.getSPStandardDialect(context);
    String roleAttr = null;

    if (spStandardDialect != null && DefaultSequenceHandlerUtils.isLocalClaimDialect(context)) {
        spRoleUri = DefaultSequenceHandlerUtils.getStandardRoleClaimURI(spStandardDialect,
                context.getTenantDomain());
        roleAttr = mappedAttrs.get(spRoleUri);
    } else if (spStandardDialect != null && !DefaultSequenceHandlerUtils.isLocalClaimDialect(context)) {
        String localClaim =
                DefaultSequenceHandlerUtils.getSPMappedLocalRoleClaimURI(sequenceConfig.getApplicationConfig());
        spRoleUri = DefaultSequenceHandlerUtils.getStandardClaimURIFromLocal(spStandardDialect,
                context.getTenantDomain(), localClaim);
        roleAttr = mappedAttrs.get(spRoleUri);
    } else if (spStandardDialect == null && DefaultSequenceHandlerUtils.isLocalClaimDialect(context)) {
        roleAttr = mappedAttrs.get(spRoleUri);
    } else if (spStandardDialect == null && !DefaultSequenceHandlerUtils.isLocalClaimDialect(context)) {
        roleAttr = mappedAttrs.get(spRoleUri);
    }

    if (StringUtils.isNotBlank(roleAttr)) {
        // Need to convert multiAttributeSeparator value into a regex literal before calling
        // split function. Otherwise split can produce misleading results in case
        // multiAttributeSeparator contains regex special meaning characters like .*
        return roleAttr.split(Pattern.quote(FrameworkUtils.getMultiAttributeSeparator()));
    }

    return null;
}
 
Example #26
Source File: DefaultStepBasedSequenceHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param context
 * @param mappedRoles
 * @param extAttributesValueMap
 */
protected void handleJitProvisioning(String subjectIdentifier, AuthenticationContext context,
                                     List<String> mappedRoles, Map<String, String> extAttributesValueMap)
        throws FrameworkException {

    try {
        @SuppressWarnings("unchecked")
        String userStoreDomain = null;
        String provisioningClaimUri = context.getExternalIdP()
                .getProvisioningUserStoreClaimURI();
        String provisioningUserStoreId = context.getExternalIdP().getProvisioningUserStoreId();

        if (provisioningUserStoreId != null) {
            userStoreDomain = provisioningUserStoreId;
        } else if (provisioningClaimUri != null) {
            userStoreDomain = extAttributesValueMap.get(provisioningClaimUri);
        }

        // setup thread local variable to be consumed by the provisioning
        // framework.
        ThreadLocalProvisioningServiceProvider serviceProvider = new ThreadLocalProvisioningServiceProvider();
        serviceProvider.setServiceProviderName(context.getSequenceConfig()
                                                       .getApplicationConfig().getApplicationName());
        serviceProvider.setJustInTimeProvisioning(true);
        serviceProvider.setClaimDialect(ApplicationConstants.LOCAL_IDP_DEFAULT_CLAIM_DIALECT);
        serviceProvider.setTenantDomain(context.getTenantDomain());
        IdentityApplicationManagementUtil
                .setThreadLocalProvisioningServiceProvider(serviceProvider);

        FrameworkUtils.getProvisioningHandler().handle(mappedRoles, subjectIdentifier,
                                                       extAttributesValueMap, userStoreDomain, context.getTenantDomain());

    } catch (FrameworkException e) {
        log.error("User provisioning failed!", e);
    } finally {
        IdentityApplicationManagementUtil.resetThreadLocalProvisioningServiceProvider();
    }
}
 
Example #27
Source File: AsyncSequenceExecutor.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public void exec(AsyncCaller caller, AsyncReturn returnFunction, AuthenticationContext authenticationContext) throws FrameworkException {

        if (returnFunction == null) {
            throw new FrameworkException("Can not execute the async process, as no callback function registered on " +
                    "returnFunction.");
        }

        AsyncReturn wrappedReturn = (ctx, m, r) -> {
            this.execReturn(returnFunction, ctx, m, r);
        };

        executorService.submit(
                new AsyncCallerTask(
                        new ObservingAsyncProcess(caller, wrappedReturn, authenticationContext)));
    }
 
Example #28
Source File: DefaultStepBasedSequenceHandlerTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandlePassiveAuthenticateWhenMultiOptionStep() throws Exception {

    StepHandler stepHandler = getMockedStepHandlerForSuccessfulRequestAuthentication();
    mockStatic(FrameworkUtils.class);
    when(FrameworkUtils.getStepHandler()).thenReturn(stepHandler);

    StepConfig firstStep = new StepConfig();
    firstStep.setOrder(1);

    // Second step is completed.
    StepConfig lastStep = new StepConfig();
    lastStep.setMultiOption(true);
    lastStep.setOrder(2);
    lastStep.setCompleted(true);

    SequenceConfig sequenceConfig = new SequenceConfig();
    sequenceConfig.getStepMap().put(1, firstStep);
    sequenceConfig.getStepMap().put(2, lastStep);

    doNothing().when(stepBasedSequenceHandler).handlePostAuthentication(any(HttpServletRequest.class), any
            (HttpServletResponse.class), any(AuthenticationContext.class));

    // currently we have completed second step
    context.setCurrentStep(2);
    context.setSequenceConfig(sequenceConfig);
    context.setPassiveAuthenticate(true);
    context.setRequestAuthenticated(false);

    stepBasedSequenceHandler.handle(request, response, context);
    assertResetContext(context);
    assertTrue(context.getSequenceConfig().isCompleted());
    assertFalse(context.getSequenceConfig().getStepMap().get(context.getCurrentStep()).isRetrying());
}
 
Example #29
Source File: DefaultAuthenticationRequestHandlerTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "rememberMeParamProvider")
public void testHandleRememberMeOptionFromLoginPage(String rememberMeParam,
                                                    boolean expectedResult) throws Exception {

    doReturn(rememberMeParam).when(request).getParameter(FrameworkConstants.RequestParams.REMEMBER_ME);

    AuthenticationContext context = spy(new AuthenticationContext());
    SequenceConfig sequenceConfig = spy(new SequenceConfig());
    when(sequenceConfig.isCompleted()).thenReturn(true);
    ServiceProvider serviceProvider = spy(new ServiceProvider());
    LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig = spy(new
        LocalAndOutboundAuthenticationConfig());
    when(localAndOutboundAuthenticationConfig.getAuthenticationType()).thenReturn(ApplicationConstants
        .AUTH_TYPE_LOCAL);
    serviceProvider.setLocalAndOutBoundAuthenticationConfig(localAndOutboundAuthenticationConfig);
    ApplicationConfig applicationConfig = spy(new ApplicationConfig(serviceProvider));
    sequenceConfig.setApplicationConfig(applicationConfig);

    context.setSequenceConfig(sequenceConfig);

    // mock the context to show that flow is returning back from login page
    when(context.isReturning()).thenReturn(true);
    when(context.getCurrentStep()).thenReturn(0);

    DefaultAuthenticationRequestHandler authenticationRequestHandler =
            spy(new DefaultAuthenticationRequestHandler());

    // Mock conclude flow and post authentication flows to isolate remember me option
    doNothing().when(authenticationRequestHandler).concludeFlow(request, response, context);

    authenticationRequestHandler.handle(request, response, context);

    assertEquals(context.isRememberMe(), expectedResult);
}
 
Example #30
Source File: DefaultStepBasedSequenceHandlerTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleClaimMappings() throws Exception {
    ClaimHandler claimHandler = Util.mockClaimHandler();
    mockStatic(FrameworkUtils.class);
    when(FrameworkUtils.getClaimHandler()).thenReturn(claimHandler);

    Map<String, String> claims = stepBasedSequenceHandler.handleClaimMappings(
            null,
            new AuthenticationContext(),
            new HashMap<String, String>(),
            false);
    assertNotNull(claims);
}