org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser Java Examples

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser. 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: 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 #2
Source File: RoleBasedScopesIssuer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to retrieve authorized scopes with respect to an authorization callback.
 *
 * @param scopeValidationCallback Authorization callback to validate scopes
 * @param whiteListedScopes       scopes to be white listed
 * @return authorized scopes list
 */
@Override
public List<String> getScopes(OAuthCallback scopeValidationCallback, List<String> whiteListedScopes) {

    List<String> authorizedScopes = null;
    String[] requestedScopes = scopeValidationCallback.getRequestedScope();
    String clientId = scopeValidationCallback.getClient();
    AuthenticatedUser authenticatedUser = scopeValidationCallback.getResourceOwner();

    Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser);
    if (appScopes != null) {
        //If no scopes can be found in the context of the application
        if (isAppScopesEmpty(appScopes, clientId)) {
            return getAllowedScopes(whiteListedScopes, Arrays.asList(requestedScopes));
        }
        String[] userRoles = getUserRoles(authenticatedUser);
        authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes, whiteListedScopes);
    }
    return authorizedScopes;
}
 
Example #3
Source File: FIDOAuthenticator.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 {

    String tokenResponse = request.getParameter("tokenResponse");
    if (tokenResponse != null && !tokenResponse.contains("errorCode")) {
        String appID = FIDOUtil.getOrigin(request);
        AuthenticatedUser user = getUsername(context);

        U2FService u2FService = U2FService.getInstance();
        FIDOUser fidoUser = new FIDOUser(user.getUserName(), user.getTenantDomain(),
                                         user.getUserStoreDomain(), AuthenticateResponse.fromJson(tokenResponse));
        fidoUser.setAppID(appID);
        u2FService.finishAuthentication(fidoUser);
        context.setSubject(user);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("FIDO authentication filed : " + tokenResponse);
        }

        throw new InvalidCredentialsException("FIDO device authentication failed ");
    }

}
 
Example #4
Source File: OpenIDConnectUserRPStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param user
 * @param appName
 * @throws OAuthSystemException
 */
public void putUserRPToStore(AuthenticatedUser user, String appName, boolean trustedAlways, String clientId) throws
        OAuthSystemException {
    OpenIDUserRPDO repDO = new OpenIDUserRPDO();
    repDO.setDefaultProfileName(DEFAULT_PROFILE_NAME);
    repDO.setRpUrl(appName);
    repDO.setUserName(user.getAuthenticatedSubjectIdentifier());
    repDO.setTrustedAlways(trustedAlways);
    int tenantId = -1;
    if (user.getUserName() != null) {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } else {
        OAuthAppDAO oAuthAppDAO = new OAuthAppDAO();
        OAuthAppDO appDO;
        try {
            appDO = oAuthAppDAO.getAppInformation(clientId);
            tenantId = IdentityTenantUtil.getTenantId(appDO.getUser().getTenantDomain());
        } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
            throw new OAuthSystemException("Error while retrieving app");
        }
    }

    OpenIDUserRPDAO dao = new OpenIDUserRPDAO();
    dao.createOrUpdate(repDO, tenantId);
}
 
Example #5
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 #6
Source File: DefaultClaimHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private AuthenticatedUser getAuthenticatedUser(StepConfig stepConfig, AuthenticationContext context) {

        AuthenticatedUser authenticatedUser;
        if (stepConfig != null) {
            // Calling from StepBasedSequenceHandler.
            authenticatedUser = stepConfig.getAuthenticatedUser();
            if (log.isDebugEnabled()) {
                log.debug("Authenticated user found from step config.");
            }
        } else {
            // Calling from RequestPathBasedSequenceHandler.
            authenticatedUser = context.getSequenceConfig().getAuthenticatedUser();
            if (log.isDebugEnabled()) {
                log.debug("Authenticated user found from authentication context.");
            }
        }
        return authenticatedUser;
    }
 
Example #7
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 #8
Source File: FrameworkUtils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated This method is a temporary solution and might get changed in the future.
 * It is recommended not use this method.
 *
 * @param context AuthenticationContext.
 * @return true if the handlers need to be executed, otherwise false.
 */
@Deprecated
public static boolean isStepBasedSequenceHandlerExecuted(AuthenticationContext context) {

    boolean isNeeded = true;
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    AuthenticatedUser authenticatedUser = sequenceConfig.getAuthenticatedUser();
    Object isDefaultStepBasedSequenceHandlerTriggered = context
            .getProperty(FrameworkConstants.STEP_BASED_SEQUENCE_HANDLER_TRIGGERED);
    // If authenticated user is null or if step based sequence handler is not trigged, exit the flow.
    if (authenticatedUser == null || isDefaultStepBasedSequenceHandlerTriggered == null
            || !(boolean) isDefaultStepBasedSequenceHandlerTriggered) {
        isNeeded = false;
    }
    return isNeeded;
}
 
Example #9
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 #10
Source File: FIDOAuthenticator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private AuthenticatedUser getUsername(AuthenticationContext context) throws AuthenticationFailedException {
    //username from authentication context.
    AuthenticatedUser authenticatedUser = null;
    for (int i = 1; i <= context.getSequenceConfig().getStepMap().size(); i++) {
        StepConfig stepConfig = context.getSequenceConfig().getStepMap().get(i);
        if (stepConfig.getAuthenticatedUser() != null && stepConfig.getAuthenticatedAutenticator()
                .getApplicationAuthenticator() instanceof LocalApplicationAuthenticator) {
            authenticatedUser = stepConfig.getAuthenticatedUser();
            if (authenticatedUser.getUserStoreDomain() == null) {
                authenticatedUser.setUserStoreDomain(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME);
            }


            if (log.isDebugEnabled()) {
                log.debug("username :" + authenticatedUser.toString());
            }
            break;
        }
    }
    if(authenticatedUser == null){
        throw new AuthenticationFailedException("Could not locate an authenticated username from previous steps " +
                "of the sequence. Hence cannot continue with FIDO authentication.");
    }
    return authenticatedUser;
}
 
Example #11
Source File: GraphBasedStepHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleFailedAuthentication(HttpServletRequest request, HttpServletResponse response,
                                          AuthenticationContext context, AuthenticatorConfig authenticatorConfig,
                                          User user) {

    super.handleFailedAuthentication(request, response, context, authenticatorConfig, user);

    if (user != null) {
        AuthenticatedUser lastAttemptedUser = buildAuthenticatedUser(user);
        context.setProperty(FrameworkConstants.JSAttributes.JS_LAST_LOGIN_FAILED_USER, lastAttemptedUser);
        if (log.isDebugEnabled()) {
            log.debug("Last attempted user : " + lastAttemptedUser.toFullQualifiedUsername() + " is set in the " +
                    "authentication context for failed login attempt to service provider: " +
                    context.getServiceProviderName());
        }
    }

    request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.FAIL_COMPLETED);
    if (log.isDebugEnabled()) {
        log.debug("Authentication flow status set to '" + AuthenticatorFlowStatus.FAIL_COMPLETED + "' for " +
                "authentication attempt made to service provider: " + context.getServiceProviderName());
    }
}
 
Example #12
Source File: CellerySignedJWTGenerator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private String getEndUserName(TokenValidationContext validationContext) throws APIManagementException {

        try {
            String accessToken = validationContext.getAccessToken();
            AccessTokenDO tokenInfo = OAuth2Util.getAccessTokenDOfromTokenIdentifier(accessToken);
            AuthenticatedUser authzUser = tokenInfo.getAuthzUser();
            String endUserName = validationContext.getValidationInfoDTO().getEndUserName();
            if (authzUser.isFederatedUser()) {
                return endUserName;
            } else {
                return MultitenantUtils.getTenantAwareUsername(endUserName);
            }
        } catch (IdentityOAuth2Exception e) {
            throw new APIManagementException("Error while retrieving authenticated user metadata.", e);
        }

    }
 
Example #13
Source File: SSOConsentServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Process the provided user consent and creates a consent receipt.
 *
 * @param consentApprovedClaimIds Consent approved claims by the user.
 * @param serviceProvider         Service provider receiving consent.
 * @param authenticatedUser       Authenticated user providing consent.
 * @param consentClaimsData       Claims which the consent requested for.
 * @throws SSOConsentServiceException If error occurs while processing user consent.
 */
@Override
public void processConsent(List<Integer> consentApprovedClaimIds, ServiceProvider serviceProvider,
                           AuthenticatedUser authenticatedUser, ConsentClaimsData consentClaimsData)
        throws SSOConsentServiceException {

    if (!isSSOConsentManagementEnabled(serviceProvider)) {
        String message = "Consent management for SSO is disabled.";
        throw new SSOConsentDisabledException(message, message);
    }
    if (isDebugEnabled()) {
        logDebug("User: " + authenticatedUser.getAuthenticatedSubjectIdentifier() + " has approved consent.");
    }
    UserConsent userConsent = processUserConsent(consentApprovedClaimIds, consentClaimsData);
    String subject = buildSubjectWithUserStoreDomain(authenticatedUser);
    List<ClaimMetaData> claimsWithConsent = getAllUserApprovedClaims(serviceProvider, authenticatedUser,
            userConsent);
    String spTenantDomain = getSPTenantDomain(serviceProvider);
    String subjectTenantDomain = authenticatedUser.getTenantDomain();

    if (isNotEmpty(claimsWithConsent)) {
        addReceipt(subject, subjectTenantDomain, serviceProvider, spTenantDomain, claimsWithConsent);
    }
}
 
Example #14
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 #15
Source File: DefaultRequestCoordinator.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the given user is disabled and returns true for disabled users
 * @param userStoreManager
 * @param user
 * @return boolean
 * @throws FrameworkException
 */
private boolean isUserDisabled(UserStoreManager userStoreManager, AuthenticatedUser user)
        throws FrameworkException {

    if (!isAccountDisablingEnabled(user.getTenantDomain())) {
        return false;
    }

    String accountDisabledClaimValue = getClaimValue(
            user.getUserName(), userStoreManager, ACCOUNT_DISABLED_CLAIM_URI);
    return Boolean.parseBoolean(accountDisabledClaimValue);

}
 
Example #16
Source File: JITProvisioningPostAuthenticationHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * To get the final claims that need to be stored against user by combining the claims from IDP as well as from
 * User entered claims.
 *
 * @param request          Http servlet request.
 * @param localClaimValues Relevant local claim values from IDP.
 * @param context          AuthenticationContext.
 * @return combination of claims came from IDP and the claims user has filed.
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception.
 */
private Map<String, String> getCombinedClaims(HttpServletRequest request, Map<String, String> localClaimValues,
        AuthenticationContext context) throws PostAuthenticationFailedException {

    String externalIdPConfigName = context.getExternalIdP().getIdPName();
    org.wso2.carbon.user.api.ClaimMapping[] claims = getClaimsForTenant(context.getTenantDomain(),
            externalIdPConfigName);
    Map<String, String> missingClaims = new HashMap<>();
    if (claims != null) {
        for (org.wso2.carbon.user.api.ClaimMapping claimMapping : claims) {
            String uri = claimMapping.getClaim().getClaimUri();
            String claimValue = request.getParameter(uri);

            if (StringUtils.isNotBlank(claimValue) && StringUtils.isEmpty(localClaimValues.get(uri))) {
                localClaimValues.put(uri, claimValue);
            } else {
                /* Claims that are mandatory from service provider level will pre-appended with "missing-" in
                 there name.
                 */
                claimValue = request.getParameter("missing-" + uri);
                if (StringUtils.isNotEmpty(claimValue)) {
                    localClaimValues.put(uri, claimValue);
                    missingClaims.put(uri, claimValue);
                }
            }
        }
    }
    // Handle the missing claims.
    if (MapUtils.isNotEmpty(missingClaims)) {
        AuthenticatedUser authenticatedUser = context.getSequenceConfig().getAuthenticatedUser();
        Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes();
        userAttributes.putAll(FrameworkUtils.buildClaimMappings(missingClaims));
        authenticatedUser.setUserAttributes(userAttributes);
        context.getSequenceConfig().setAuthenticatedUser(authenticatedUser);
    }
    return localClaimValues;
}
 
Example #17
Source File: JITProvisioningPostAuthenticationHandlerTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * To get the authentication context and to call the handle method of the PostJitProvisioningHandler.
 *
 * @param sp1 Service Provider
 * @return relevant authentication context.
 * @throws FrameworkException Framwork Exception.
 */
private AuthenticationContext processAndGetAuthenticationContext(ServiceProvider sp1, boolean
        withAuthenticatedUser, boolean isFederated) throws FrameworkException {

    AuthenticationContext context = getAuthenticationContext(sp1);
    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);
    context.setProperty(FrameworkConstants.STEP_BASED_SEQUENCE_HANDLER_TRIGGERED, true);

    ApplicationAuthenticator applicationAuthenticator = mock(ApplicationAuthenticator.class);

    if (isFederated) {
        applicationAuthenticator = mock(FederatedApplicationAuthenticator.class);
    }
    when(applicationAuthenticator.getName()).thenReturn("Authenticator1");

    if (withAuthenticatedUser) {
        AuthenticatedUser authenticatedUser = new AuthenticatedUser();
        authenticatedUser.setUserName("test");
        authenticatedUser.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        authenticatedUser.setAuthenticatedSubjectIdentifier("test");
        sequenceConfig.setAuthenticatedUser(authenticatedUser);

        AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig();
        authenticatorConfig.setApplicationAuthenticator(applicationAuthenticator);
        for (Map.Entry<Integer, StepConfig> entry : sequenceConfig.getStepMap().entrySet()) {
            StepConfig stepConfig = entry.getValue();
            stepConfig.setAuthenticatedAutenticator(authenticatorConfig);
            stepConfig.setAuthenticatedUser(authenticatedUser);
        }
        context.setSequenceConfig(sequenceConfig);
    }

    UserCoreUtil.setDomainInThreadLocal("test_domain");
    return context;
}
 
Example #18
Source File: AuthzCodeDO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public AuthzCodeDO(AuthenticatedUser authorizedUser, String[] scope, Timestamp issuedTime, long validityPeriod, String
        callbackUrl, String consumerKey, String authorizationCode, String authzCodeId) {
    this.authorizedUser = authorizedUser;
    this.scope = scope;
    this.issuedTime = issuedTime;
    this.validityPeriod = validityPeriod;
    this.callbackUrl = callbackUrl;
    this.consumerKey = consumerKey;
    this.authorizationCode = authorizationCode;
    this.authzCodeId = authzCodeId;
}
 
Example #19
Source File: JsAuthenticationContext.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private JsAuthenticatedUser getLastLoginFailedUserFromWrappedContext() {

        Object lastLoginFailedUser = getWrapped().getProperty(FrameworkConstants.JSAttributes.JS_LAST_LOGIN_FAILED_USER);
        if (lastLoginFailedUser instanceof AuthenticatedUser) {
            return new JsAuthenticatedUser(getWrapped(), (AuthenticatedUser) lastLoginFailedUser);
        } else {
            return null;
        }
    }
 
Example #20
Source File: DefaultRequestCoordinator.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void publishAuthenticationFailure(HttpServletRequest request, AuthenticationContext context,
        AuthenticatedUser user) {

    AuthenticationDataPublisher authnDataPublisherProxy = FrameworkServiceDataHolder.getInstance()
            .getAuthnDataPublisherProxy();

    if (authnDataPublisherProxy != null && authnDataPublisherProxy.isEnabled(context)) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(FrameworkConstants.AnalyticsAttributes.USER, user);
        Map<String, Object> unmodifiableParamMap = Collections.unmodifiableMap(paramMap);
        authnDataPublisherProxy.publishAuthenticationFailure(request, context, unmodifiableParamMap);
    }
}
 
Example #21
Source File: DefaultClaimHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private AuthenticatedUser getAuthenticatedUser(StepConfig stepConfig, AuthenticationContext context) {
    AuthenticatedUser authenticatedUser;
    if (stepConfig != null) {
        //calling from StepBasedSequenceHandler
        authenticatedUser = stepConfig.getAuthenticatedUser();
    } else {
        //calling from RequestPathBasedSequenceHandler
        authenticatedUser = context.getSequenceConfig().getAuthenticatedUser();
    }
    return authenticatedUser;
}
 
Example #22
Source File: DefaultAuthenticationRequestHandlerTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void setUser(AuthenticationContext context, String userName) {

        AuthenticatedUser authenticatedUser = new AuthenticatedUser();
        authenticatedUser.setAuthenticatedSubjectIdentifier(userName);
        context.setProperty("user-tenant-domain", MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        context.getSequenceConfig().setAuthenticatedUser(authenticatedUser);
    }
 
Example #23
Source File: DefaultAuthenticationRequestHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void publishAuthenticationSuccess(HttpServletRequest request, AuthenticationContext context,
                                          AuthenticatedUser user) {

    AuthenticationDataPublisher authnDataPublisherProxy = FrameworkServiceDataHolder.getInstance()
            .getAuthnDataPublisherProxy();
    if (authnDataPublisherProxy != null && authnDataPublisherProxy.isEnabled(context)) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(FrameworkConstants.AnalyticsAttributes.USER, user);
        Map<String, Object> unmodifiableParamMap = Collections.unmodifiableMap(paramMap);
        authnDataPublisherProxy.publishAuthenticationSuccess(request, context,
                unmodifiableParamMap);

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

    // mock the behaviour of the request path authenticator
    when(requestPathAuthenticator.canHandle(any(HttpServletRequest.class))).thenReturn(true);
    doReturn(AuthenticatorFlowStatus.SUCCESS_COMPLETED).when(requestPathAuthenticator)
            .process(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AuthenticationContext.class));

    String subjectIdentifier = "H2/[email protected]";
    AuthenticatedUser authenticatedUser = new AuthenticatedUser();
    authenticatedUser.setAuthenticatedSubjectIdentifier(subjectIdentifier);
    authenticatedUser.setFederatedUser(false);

    context.setSubject(authenticatedUser);

    mockStatic(FrameworkUtils.class);
    when(FrameworkUtils.getMultiAttributeSeparator()).thenReturn(",");

    requestPathBasedSequenceHandler = spy(new DefaultRequestPathBasedSequenceHandler());
    // mock triggering post authentication
    doNothing().when(requestPathBasedSequenceHandler).handlePostAuthentication(any(HttpServletRequest.class), any
            (HttpServletResponse.class), any(AuthenticationContext.class), any(AuthenticatedIdPData.class));

    requestPathBasedSequenceHandler.handle(request, response, context);

    assertEquals(context.getSequenceConfig().isCompleted(), true);
    assertNotNull(context.getCurrentAuthenticatedIdPs());
    assertEquals(context.getCurrentAuthenticatedIdPs().size(), 1);

    AuthenticatedIdPData authenticatedIdPData = context.getCurrentAuthenticatedIdPs()
            .get(FrameworkConstants.LOCAL_IDP_NAME);

    assertNotNull(authenticatedIdPData);
    assertEquals(authenticatedIdPData.getIdpName(), FrameworkConstants.LOCAL_IDP_NAME);
    assertNotNull(authenticatedIdPData.getUser());
    assertEquals(authenticatedIdPData.getUser().getAuthenticatedSubjectIdentifier(), subjectIdentifier);
    assertEquals(authenticatedIdPData.getAuthenticator(), authenticatorConfig);
}
 
Example #25
Source File: JsClaims.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Get authenticated user from step config of current subject identifier.
 *
 * @return AuthenticatedUser.
 */
private AuthenticatedUser getAuthenticatedUserFromSubjectIdentifierStep() {

    AuthenticatedUser authenticatedUser = null;
    StepConfig stepConfig = getCurrentSubjectIdentifierStep();
    if (stepConfig != null) {
        authenticatedUser = getCurrentSubjectIdentifierStep().getAuthenticatedUser();
    }
    return authenticatedUser;
}
 
Example #26
Source File: DefaultClaimHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void addMultiAttributeSperatorToRequestedClaims(AuthenticatedUser authenticatedUser,
                                                        org.wso2.carbon.user.core.UserStoreManager userStore,
                                                        Map<String, String> spRequestedClaims) {
    if (!spRequestedClaims.isEmpty()) {
        RealmConfiguration realmConfiguration = userStore.getRealmConfiguration();

        String claimSeparator = realmConfiguration.getUserStoreProperty(IdentityCoreConstants
                .MULTI_ATTRIBUTE_SEPARATOR);
        if (StringUtils.isNotBlank(claimSeparator)) {
            spRequestedClaims.putIfAbsent(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR, claimSeparator);
        }
    }
}
 
Example #27
Source File: DefaultClaimHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private Map<String, String> retrieveAllNunNullUserClaimValues(AuthenticatedUser authenticatedUser,
        ClaimManager claimManager, ApplicationConfig appConfig,
        org.wso2.carbon.user.core.UserStoreManager userStore) throws FrameworkException {

    String tenantDomain = authenticatedUser.getTenantDomain();
    String tenantAwareUserName = authenticatedUser.getUserName();

    Map<String, String> allLocalClaims = new HashMap<>();
    try {

        org.wso2.carbon.user.api.ClaimMapping[] claimMappings = claimManager
                .getAllClaimMappings(ApplicationConstants.LOCAL_IDP_DEFAULT_CLAIM_DIALECT);
        List<String> localClaimURIs = new ArrayList<>();
        for (org.wso2.carbon.user.api.ClaimMapping mapping : claimMappings) {
            String claimURI = mapping.getClaim().getClaimUri();
            localClaimURIs.add(claimURI);
        }
        allLocalClaims = userStore.getUserClaimValues(tenantAwareUserName,
                localClaimURIs.toArray(new String[localClaimURIs.size()]), null);

        if (allLocalClaims == null) {
            return new HashMap<>();
        }
    } catch (UserStoreException e) {
        if (e.getMessage().contains("UserNotFound")) {
            if (log.isDebugEnabled()) {
                log.debug("User " + tenantAwareUserName + " not found in user store");
            }
        } else {
            throw new FrameworkException("Error occurred while getting all user claims for " +
                    authenticatedUser + " in " + tenantDomain, e);
        }
    }
    return allLocalClaims;
}
 
Example #28
Source File: SessionDataPublisherImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Method to build a AuthenticatedUser type object
 * @param authenticatedUser required param
 * @return AuthenticatedUser type object
 * @throws IdentityOAuth2Exception exception
 */
private AuthenticatedUser buildAuthenticatedUser(AuthenticatedUser authenticatedUser)
        throws IdentityOAuth2Exception {

    AuthenticatedUser user = new AuthenticatedUser();
    String tenantAwareusername = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    user.setUserName(UserCoreUtil.removeDomainFromName(tenantAwareusername));
    user.setTenantDomain(tenantDomain);
    user.setUserStoreDomain(IdentityUtil.extractDomainFromName(tenantAwareusername));
    user.setFederatedUser(true);
    user.setUserStoreDomain(OAuth2Util.getUserStoreForFederatedUser(authenticatedUser));
    return user;
}
 
Example #29
Source File: OAuthAdminService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Update existing consumer application.
 *
 * @param consumerAppDTO <code>OAuthConsumerAppDTO</code> with updated application information
 * @throws IdentityOAuthAdminException Error when updating the underlying identity persistence store.
 */
public void updateConsumerApplication(OAuthConsumerAppDTO consumerAppDTO) throws IdentityOAuthAdminException {
    String userName = CarbonContext.getThreadLocalCarbonContext().getUsername();
    String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userName);
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    OAuthAppDAO dao = new OAuthAppDAO();
    OAuthAppDO oauthappdo = new OAuthAppDO();
    AuthenticatedUser user = new AuthenticatedUser();
    user.setUserName(UserCoreUtil.removeDomainFromName(tenantAwareUsername));
    user.setTenantDomain(tenantDomain);
    user.setUserStoreDomain(IdentityUtil.extractDomainFromName(userName));
    oauthappdo.setUser(user);
    oauthappdo.setOauthConsumerKey(consumerAppDTO.getOauthConsumerKey());
    oauthappdo.setOauthConsumerSecret(consumerAppDTO.getOauthConsumerSecret());
    oauthappdo.setCallbackUrl(consumerAppDTO.getCallbackUrl());
    oauthappdo.setApplicationName(consumerAppDTO.getApplicationName());
    if (OAuthConstants.OAuthVersions.VERSION_2.equals(consumerAppDTO.getOAuthVersion())) {
        List<String> allowedGrants = new ArrayList<>(Arrays.asList(getAllowedGrantTypes()));
        String[] requestGrants = consumerAppDTO.getGrantTypes().split("\\s");
        for (String requestedGrant : requestGrants) {
            if (StringUtils.isBlank(requestedGrant)) {
                continue;
            }
            if (!allowedGrants.contains(requestedGrant)) {
                throw new IdentityOAuthAdminException(requestedGrant + " not allowed");
            }
        }
        oauthappdo.setGrantTypes(consumerAppDTO.getGrantTypes());
    }
    dao.updateConsumerApplication(oauthappdo);
    if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
        appInfoCache.addToCache(oauthappdo.getOauthConsumerKey(), oauthappdo);
    }
}
 
Example #30
Source File: ExtendedClientCredentialsGrantHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    boolean validateResult = super.validateGrant(tokReqMsgCtx);
    AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
    String username = user.getUserName();
    user.setUserName(username);
    tokReqMsgCtx.setAuthorizedUser(user);

    return validateResult;
}