org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils Java Examples

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils. 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
@Test
public void testHandleSingleStepFinish() throws Exception {
    // mock the step handler
    StepHandler stepHandler = getMockedStepHandlerForSuccessfulRequestAuthentication();
    mockStatic(FrameworkUtils.class);
    when(FrameworkUtils.getStepHandler()).thenReturn(stepHandler);

    StepConfig stepConfig = new StepConfig();
    SequenceConfig sequenceConfig = new SequenceConfig();
    sequenceConfig.getStepMap().put(1, stepConfig);
    context.setSequenceConfig(sequenceConfig);

    doNothing().when(stepBasedSequenceHandler).handlePostAuthentication(any(HttpServletRequest.class), any
            (HttpServletResponse.class), any(AuthenticationContext.class));
    stepBasedSequenceHandler.handle(request, response, context);

    assertTrue(context.getSequenceConfig().isCompleted());
    assertTrue(context.isRequestAuthenticated());
    assertResetContext(context);
}
 
Example #2
Source File: UserSessionManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the active sessions from given list of session IDs.
 *
 * @param sessionIdList list of sessionIds
 * @return list of user sessions
 * @throws SessionManagementServerException if an error occurs when retrieving the UserSessions.
 */
private List<UserSession> getActiveSessionList(List<String> sessionIdList) throws SessionManagementServerException {

    List<UserSession> sessionsList = new ArrayList<>();
    for (String sessionId : sessionIdList) {
        if (sessionId != null) {
            SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(sessionId);
            if (sessionContext != null) {
                UserSessionDAO userSessionDTO = new UserSessionDAOImpl();
                UserSession userSession = userSessionDTO.getSession(sessionId);
                if (userSession != null) {
                    sessionsList.add(userSession);
                }
            }
        }
    }
    return sessionsList;
}
 
Example #3
Source File: JsGraphBuilder.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a function to show a prompt in Javascript code.
 *
 * @param templateId Identifier of the template
 * @param parameters parameters
 */
@SuppressWarnings("unchecked")
public void addShowPrompt(String templateId, Object... parameters) {

    ShowPromptNode newNode = new ShowPromptNode();
    newNode.setTemplateId(templateId);

    if (parameters.length == 2) {
        newNode.setData((Map<String, Serializable>) FrameworkUtils.toJsSerializable(parameters[0]));
    }
    if (currentNode == null) {
        result.setStartNode(newNode);
    } else {
        attachToLeaf(currentNode, newNode);
    }

    currentNode = newNode;
    if (parameters.length > 0) {
        if (parameters[parameters.length - 1] instanceof Map) {
            addEventListeners(newNode, (Map<String, Object>) parameters[parameters.length - 1]);
        } else {
            log.error("Invalid argument and hence ignored. Last argument should be a Map of event listeners.");
        }

    }
}
 
Example #4
Source File: PostAuthenticatedSubjectIdentifierHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public PostAuthnHandlerFlowStatus handle(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) {

    if (!FrameworkUtils.isStepBasedSequenceHandlerExecuted(context)) {
        return SUCCESS_COMPLETED;
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    String subjectClaimURI = sequenceConfig.getApplicationConfig().getSubjectClaimUri();
    String subjectValue = (String) context.getProperty(FrameworkConstants.SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE);
    if (StringUtils.isNotBlank(subjectClaimURI)) {
        if (subjectValue != null) {
            handleUserStoreAndTenantDomain(sequenceConfig, subjectValue);
        } else {
            log.warn("Subject claim could not be found. Defaulting to Name Identifier.");
            setAuthenticatedSujectIdentifierBasedOnUserName(sequenceConfig);
        }
    } else {
        setAuthenticatedSujectIdentifierBasedOnUserName(sequenceConfig);

    }
    return SUCCESS_COMPLETED;
}
 
Example #5
Source File: UserSessionStore.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private Set<String> getSessionsTerminated(Connection connection) throws SQLException {

        Set<String> terminatedSessionIds = new HashSet<>();

        /**
         * Retrieve only sessions which have an expiry time less than the current time.
         * As the session cleanup task deletes only entries matching the same condition, in case sessions that are
         * being marked as deleted are also retrieved that might load a huge amount of entries to the memory all the
         * time. Yet those entries will be removed from the IDN_AUTH_USER_SESSION_MAPPING_TABLE table on the first
         * execution, and there after every time the loop will be executed and the table will be scanned for a non
         * existing entry.
         */
        try (PreparedStatement preparedStatement = connection.prepareStatement(SQLQueries
                .SQL_SELECT_TERMINATED_SESSION_IDS)) {
            preparedStatement.setLong(1, FrameworkUtils.getCurrentStandardNano());
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    terminatedSessionIds.add(resultSet.getString(1));
                }
            }
        }

        return terminatedSessionIds;
    }
 
Example #6
Source File: DefaultStepBasedSequenceHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param stepConfig
 * @param context
 * @param extAttrs
 * @param isFederatedClaims
 * @return
 */
protected Map<String, String> handleClaimMappings(StepConfig stepConfig,
                                                  AuthenticationContext context, Map<String, String> extAttrs,
                                                  boolean isFederatedClaims)
        throws FrameworkException {

    Map<String, String> mappedAttrs = new HashMap<String, String>();

    try {
        mappedAttrs = FrameworkUtils.getClaimHandler().handleClaimMappings(stepConfig, context,
                                                                           extAttrs, isFederatedClaims);
    } catch (FrameworkException e) {
        log.error("Claim handling failed!", e);
    }
    if(mappedAttrs == null){
        mappedAttrs = new HashMap<>();
    }
    return mappedAttrs;
}
 
Example #7
Source File: PostAuthenticationMgtService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void removePASTRCookie(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) {

    Object pstrCookieObj = context.getParameter(FrameworkConstants.PASTR_COOKIE);
    if (pstrCookieObj != null) {
        if (log.isDebugEnabled()) {
            log.debug("Removing post authentication sequnce tracker cookie for context : " + context
                    .getContextIdentifier());
        }
        FrameworkUtils
                .setCookie(request, response, FrameworkUtils.getPASTRCookieName(context.getContextIdentifier()),
                        pstrCookieObj.toString(), 0);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("PASTR cookie is not set to context : " + context.getContextIdentifier());
        }
    }
}
 
Example #8
Source File: PostAuthAssociationHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(description = "This test case tests the Post Authentication Association handling flow with an authenticated" +
        " user via federated IDP", dataProvider = "provideTestScenarios")
public void testHandleWithAuthenticatedUserWithFederatedIdpAssociatedToSecondaryUserStore(boolean hasSpRoleMapping)
        throws Exception {

    AuthenticationContext context = processAndGetAuthenticationContext(sp, true, true, hasSpRoleMapping);
    FederatedAssociationManager federatedAssociationManager = mock(FederatedAssociationManagerImpl.class);
    when(FrameworkUtils.getFederatedAssociationManager()).thenReturn(federatedAssociationManager);
    doReturn(SECONDARY + "/" + LOCAL_USER).when(federatedAssociationManager).getUserForFederatedAssociation
            (Mockito.anyString(), Mockito.anyString(), Mockito.anyString());

    when(FrameworkUtils.getStepBasedSequenceHandler()).thenReturn(Mockito.mock(StepBasedSequenceHandler.class));
    PostAuthnHandlerFlowStatus postAuthnHandlerFlowStatus = postAuthAssociationHandler.handle(request, response,
            context);
    AuthenticatedUser authUser = context.getSequenceConfig().getAuthenticatedUser();
    Assert.assertEquals(authUser.getUserName(), LOCAL_USER, "Post Association handler failed to set associated " +
            "username");
    Assert.assertEquals(authUser.getUserStoreDomain(), SECONDARY, "Post Association handler failed to set " +
            "associated user's domain");
    Assert.assertEquals(postAuthnHandlerFlowStatus, PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED,
            "Post Association handler failed to execute with an associated user in a secondary user store.");
    if (hasSpRoleMapping) {
        Assert.assertTrue(isSpRoleMappingSuccessful(authUser.getUserAttributes()), "SP role mapping failed.");
    }
}
 
Example #9
Source File: JITProvisioningPostAuthenticationHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@BeforeClass
protected void setupSuite() throws XMLStreamException, IdentityProviderManagementException {

    configurationLoader = new UIBasedConfigurationLoader();
    mockStatic(FrameworkUtils.class);
    mockStatic(ConfigurationFacade.class);
    ConfigurationFacade configurationFacade = mock(ConfigurationFacade.class);

    PowerMockito.when(ConfigurationFacade.getInstance()).thenReturn(configurationFacade);
    IdentityProvider identityProvider = getTestIdentityProvider("default-tp-1.xml");
    ExternalIdPConfig externalIdPConfig = new ExternalIdPConfig(identityProvider);
    Mockito.doReturn(externalIdPConfig).when(configurationFacade).getIdPConfigByName(Mockito.anyString(), Mockito
            .anyString());
    when(FrameworkUtils.isStepBasedSequenceHandlerExecuted(Mockito.any(AuthenticationContext.class)))
            .thenCallRealMethod();
    request = mock(HttpServletRequest.class);
    response = mock(HttpServletResponse.class);
    postJITProvisioningHandler = JITProvisioningPostAuthenticationHandler.getInstance();
    sp = getTestServiceProvider("default-sp-1.xml");
}
 
Example #10
Source File: JITProvisioningPostAuthenticationHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(description = "This test case tests the Post JIT provisioning handling flow with an authenticated user")
public void testHandleWithAuthenticatedUserWithFederatedIdp() throws FrameworkException,
        FederatedAssociationManagerException {

    AuthenticationContext context = processAndGetAuthenticationContext(sp, true, true);
    FederatedAssociationManager federatedAssociationManager = mock(FederatedAssociationManagerImpl.class);
    when(FrameworkUtils.getFederatedAssociationManager()).thenReturn(federatedAssociationManager);
    doReturn("test").when(federatedAssociationManager).getUserForFederatedAssociation
            (Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    when(FrameworkUtils.getStepBasedSequenceHandler()).thenReturn(Mockito.mock(StepBasedSequenceHandler.class));
    PostAuthnHandlerFlowStatus postAuthnHandlerFlowStatus = postJITProvisioningHandler
            .handle(request, response, context);
    Assert.assertEquals(postAuthnHandlerFlowStatus, PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED,
            "Post JIT provisioning handler executed while having a authenticated user without federated "
                    + "authenticator");
}
 
Example #11
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 #12
Source File: PostAuthenticationMgtService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void setPASTRCookie(AuthenticationContext context, HttpServletRequest request,
        HttpServletResponse response) {

    if (context.getParameter(FrameworkConstants.PASTR_COOKIE) != null) {
        if (log.isDebugEnabled()) {
            log.debug("PASTR cookie is already set to context : " + context.getContextIdentifier());
        }
        return;
    } else {
        if (log.isDebugEnabled()) {
            log.debug(
                    "PASTR cookie is not set to context : " + context.getContextIdentifier() + ". Hence setting the"
                            + " " + "cookie");
        }
        String pastrCookieValue = UUIDGenerator.generateUUID();
        FrameworkUtils
                .setCookie(request, response, FrameworkUtils.getPASTRCookieName(context.getContextIdentifier()),
                        pastrCookieValue, -1);
        context.addParameter(FrameworkConstants.PASTR_COOKIE, pastrCookieValue);
    }
}
 
Example #13
Source File: JITProvisioningPostAuthenticationHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * To get the associated username for the current step.
 *
 * @param idpName                        Name of IDP related with current step.
 * @param authenticatedSubjectIdentifier Authenticated subject identifier.
 * @return username associated locally.
 */
private String getLocalUserAssociatedForFederatedIdentifier(String idpName, String authenticatedSubjectIdentifier,
                                                            String tenantDomain)
        throws PostAuthenticationFailedException {

    String username = null;
    try {
        FederatedAssociationManager federatedAssociationManager = FrameworkUtils.getFederatedAssociationManager();
        username = federatedAssociationManager.getUserForFederatedAssociation(tenantDomain, idpName,
                authenticatedSubjectIdentifier);
    } catch (FederatedAssociationManagerException | FrameworkException e) {
        handleExceptions(
                String.format(ErrorMessages.ERROR_WHILE_GETTING_USERNAME_ASSOCIATED_WITH_IDP.getMessage(), idpName),
                ErrorMessages.ERROR_WHILE_GETTING_USERNAME_ASSOCIATED_WITH_IDP.getCode(), e);
    }
    return username;
}
 
Example #14
Source File: DefaultRequestPathBasedSequenceHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testHandleClaimMappings() throws Exception {

    ClaimHandler claimHandler = mock(ClaimHandler.class);
    Map<String, String> claims = new HashMap<>();
    claims.put("claim1", "value1");

    doReturn(claims).when(claimHandler).handleClaimMappings(any(StepConfig.class), any(AuthenticationContext.class),
            any(Map.class), anyBoolean());

    mockStatic(FrameworkUtils.class);
    when(FrameworkUtils.getClaimHandler()).thenReturn(claimHandler);

    claims = requestPathBasedSequenceHandler.handleClaimMappings(new AuthenticationContext());
    assertNotNull(claims);
}
 
Example #15
Source File: DefaultRequestPathBasedSequenceHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param context
 * @return
 * @throws FrameworkException
 */
protected Map<String, String> handleClaimMappings(AuthenticationContext context)
        throws FrameworkException {

    Map<String, String> mappedAttrs = null;

    try {
        mappedAttrs = FrameworkUtils.getClaimHandler().handleClaimMappings(null, context, null,
                                                                           false);
        return mappedAttrs;
    } catch (FrameworkException e) {
        log.error("Claim handling failed!", e);
    }

    return null;
}
 
Example #16
Source File: DefaultRequestPathBasedSequenceHandlerTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleClaimMappingsFailed() throws Exception {

    ClaimHandler claimHandler = mock(ClaimHandler.class);
    doThrow(new FrameworkException("Claim Handling failed"))
            .when(claimHandler)
            .handleClaimMappings(any(StepConfig.class), any(AuthenticationContext.class), any(Map.class), anyBoolean());

    mockStatic(FrameworkUtils.class);
    when(FrameworkUtils.getClaimHandler()).thenReturn(claimHandler);

    Map<String, String> claims = requestPathBasedSequenceHandler.handleClaimMappings(new AuthenticationContext());
    assertNotNull(claims);
    assertEquals(claims.size(), 0);
}
 
Example #17
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);
}
 
Example #18
Source File: CommonAuthenticationHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (FrameworkUtils.getMaxInactiveInterval() == 0) {
        FrameworkUtils.setMaxInactiveInterval(request.getSession().getMaxInactiveInterval());
    }
    FrameworkUtils.getRequestCoordinator().handle(request, response);

}
 
Example #19
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 #20
Source File: DefaultProvisioningHandlerTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "associateUserEmptyInputProvider", expectedExceptions = FrameworkException.class)
public void testAssociateUserEmptyInputs(String subject,
                                         String idp) throws Exception {

    mockStatic(FrameworkUtils.class);
    doNothing().when(FrameworkUtils.class, "startTenantFlow", "tenantDomain");
    provisioningHandler.associateUser("dummy_user_name", "DUMMY_DOMAIN", "dummy.com", subject, idp);
}
 
Example #21
Source File: FacebookAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void buildClaims(AuthenticationContext context, Map<String, Object> jsonObject)
        throws ApplicationAuthenticatorException {
    if (jsonObject != null) {
        Map<ClaimMapping, String> claims = new HashMap<ClaimMapping, String>();

        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            claims.put(ClaimMapping.build(entry.getKey(), entry.getKey(), null,
                    false), entry.getValue().toString());
            if (log.isDebugEnabled() &&
                    IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                log.debug("Adding claim mapping : " + entry.getKey() + " <> " + entry.getKey() + " : "
                        + entry.getValue());
            }

        }
        if (StringUtils.isBlank(context.getExternalIdP().getIdentityProvider().getClaimConfig().getUserClaimURI())) {
            context.getExternalIdP().getIdentityProvider().getClaimConfig().setUserClaimURI
                    (FacebookAuthenticatorConstants.EMAIL);
        }
        String subjectFromClaims = FrameworkUtils.getFederatedSubjectFromClaims(
                context.getExternalIdP().getIdentityProvider(), claims);
        if (subjectFromClaims != null && !subjectFromClaims.isEmpty()) {
            AuthenticatedUser authenticatedUser =
                    AuthenticatedUser.createFederateAuthenticatedUserFromSubjectIdentifier(subjectFromClaims);
            context.setSubject(authenticatedUser);
        } else {
            setSubject(context, jsonObject);
        }

        context.getSubject().setUserAttributes(claims);

    } else {
        if (log.isDebugEnabled()) {
            log.debug("Decoded json object is null");
        }
        throw new ApplicationAuthenticatorException("Decoded json object is null");
    }
}
 
Example #22
Source File: PassiveSTS.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private AuthenticationResult getAuthenticationResultFromCache(String sessionDataKey) {
    AuthenticationResult authResult = null;
    AuthenticationResultCacheEntry authResultCacheEntry = FrameworkUtils.getAuthenticationResultFromCache(sessionDataKey);
    if (authResultCacheEntry != null) {
        authResult = authResultCacheEntry.getResult();
    } else {
        log.error("AuthenticationResult does not exist. Probably due to cache timeout");
    }

    return authResult;
}
 
Example #23
Source File: OAuth2AuthzEndpoint.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Remove authentication result from request
 * @param req
 */
private void removeAuthenticationResult(HttpServletRequest req, String sessionDataKey) {

    if(isCacheAvailable){
        FrameworkUtils.removeAuthenticationResultFromCache(sessionDataKey);
    }else {
        req.removeAttribute(FrameworkConstants.RequestAttribute.AUTH_RESULT);
    }
}
 
Example #24
Source File: JsClaims.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the remote claim value that is mapped to the give local claim
 *
 * @param localClaimURI Local claim URI
 * @param claimValue    Value to be set
 */
private void setLocalMappedClaim(String localClaimURI, Object claimValue) {

    Map<ClaimMapping, String> idpAttributesMap = authenticatedUser.getUserAttributes();
    Map<String, String> remoteMapping = FrameworkUtils.getClaimMappings(idpAttributesMap, false);
    String mappedRemoteClaim = getRemoteClaimMappedToLocalClaim(localClaimURI, remoteMapping);
    if (mappedRemoteClaim != null) {
        setFederatedClaim(mappedRemoteClaim, String.valueOf(claimValue));
    }
}
 
Example #25
Source File: SessionManagementService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * Terminates the requested session, after validating whether the session belongs to the logged in user.
 *
 * @param sessionId
 * @return
 */
public boolean removeMySession(String sessionId) {

    if (StringUtils.isBlank(sessionId)) {
        return false;
    }
    SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(sessionId);
    // Check whether the session belongs to the logged in user.
    CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext();
    String username = carbonContext.getUsername();
    // Extract the user store domain if there is any or set to 'PRIMARY'.
    String userStoreDomain = "PRIMARY";
    String[] usernameTokens = username.split("/");
    if (usernameTokens.length > 1) {
        userStoreDomain = usernameTokens[0];
        username = usernameTokens[1];
    }

    AuthenticatedUser authenticatedUser = (AuthenticatedUser) sessionContext
            .getProperty(FrameworkConstants.AUTHENTICATED_USER);
    if (username.equals(authenticatedUser.getUserName())
            && userStoreDomain.equals(authenticatedUser.getUserStoreDomain())
            && carbonContext.getTenantDomain().equals(authenticatedUser.getTenantDomain())) {
        terminateSession(sessionContext, sessionId);
    } else { // TODO : Handle federated scenario.
        log.warn(String.format("Trying to terminate a session which does not belong to logged in user (%s). " +
                "This might be an attempt for a security breach", username));
        return false;
    }
    return true;
}
 
Example #26
Source File: SessionManagementService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public boolean removeSession(String sessionId) {

        if (StringUtils.isBlank(sessionId)) {
            return false;
        }
        // Retrieve session information from cache in order to publish event
        SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(sessionId);
        terminateSession(sessionContext, sessionId);
        return true;
    }
 
Example #27
Source File: DefaultClaimHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Specially handle role claim values.
 *
 * @param context Authentication context.
 * @param mappedAttrs Mapped claim attributes.
 */
private void handleRoleClaim(AuthenticationContext context, Map<String, String> mappedAttrs) {

    if (mappedAttrs.containsKey(FrameworkConstants.LOCAL_ROLE_CLAIM_URI)) {
        String[] groups = mappedAttrs.get(FrameworkConstants.LOCAL_ROLE_CLAIM_URI).split(Pattern
                .quote(FrameworkUtils.getMultiAttributeSeparator()));
        SequenceConfig sequenceConfig = context.getSequenceConfig();
        // Execute only if it has allowed removing userstore domain from the sp level configurations.
        if (isRemoveUserDomainInRole(sequenceConfig)) {
            mappedAttrs.put(FrameworkConstants.LOCAL_ROLE_CLAIM_URI, FrameworkUtils
                    .removeDomainFromNamesExcludeHybrid(Arrays.asList(groups)));
        }
    }
}
 
Example #28
Source File: OpenIDHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private AuthenticationResult getAuthenticationResultFromCache(String sessionDataKey) {
    AuthenticationResult authResult = null;
    AuthenticationResultCacheEntry authResultCacheEntry = FrameworkUtils.getAuthenticationResultFromCache(sessionDataKey);
    if (authResultCacheEntry != null) {
        authResult = authResultCacheEntry.getResult();
    } else {
        log.error("Cannot find AuthenticationResult from the cache");
    }

    return authResult;
}
 
Example #29
Source File: DefaultRequestCoordinator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * When cache removed authentication request stored as request attribute, then taking request from request or
 * otherwise getting authentication request from cache
 *
 * @param request
 * @param sessionDataKey
 * @return
 */
private AuthenticationRequestCacheEntry getAuthenticationRequest(HttpServletRequest request,
        String sessionDataKey) {

    AuthenticationRequestCacheEntry authRequest = getAuthenticationRequestFromRequest(request);
    if (authRequest == null) {
        authRequest = FrameworkUtils.getAuthenticationRequestFromCache(sessionDataKey);
    }
    return authRequest;
}
 
Example #30
Source File: DefaultClaimHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private Map<String, String> mapLocalSpClaimsToRemoteSPClaims(String spStandardDialect,
                                                             AuthenticationContext context,
                                                             Map<String, String> spClaimMappings)
        throws FrameworkException {
    Map<String, String> localToSPClaimMappings = null;

    if (spStandardDialect != null) {
        // passing null for keySet argument to get all claim mappings,
        // since we don't know required claim mappings in advance
        // Key:value -> carbon_dialect:standard_dialect
        try {
            localToSPClaimMappings = getClaimMappings(spStandardDialect, null,
                                                      context.getTenantDomain(), true);
        } catch (Exception e) {
            throw new FrameworkException("Error occurred while getting all claim mappings from " +
                                         spStandardDialect + " dialect to " +
                                         ApplicationConstants.LOCAL_IDP_DEFAULT_CLAIM_DIALECT + " dialect for " +
                                         context.getTenantDomain() + " to handle federated claims", e);
        }
    } else if (!spClaimMappings.isEmpty()) {
        localToSPClaimMappings = FrameworkUtils.getLocalToSPClaimMappings(spClaimMappings);
    } else { // no standard dialect and no custom claim mappings
        throw new AssertionError("Authenticator Error! Authenticator does not have a " +
                                 "standard dialect and no custom claim mappings defined for IdP");
    }
    return localToSPClaimMappings;
}