Java Code Examples for org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser#setAuthenticatedSubjectIdentifier()

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser#setAuthenticatedSubjectIdentifier() . 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: 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 2
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 3
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 4
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 5
Source File: DefaultRequestPathBasedSequenceHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
protected void handlePostAuthentication(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationContext context,
                                        AuthenticatedIdPData authenticatedIdPData) throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Handling Post Authentication tasks");
    }

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    Map<String, String> mappedAttrs;
    StringBuilder jsonBuilder = new StringBuilder();

    // build the authenticated idps JWT to send to the calling servlet.
    jsonBuilder.append("\"idps\":");
    jsonBuilder.append("[");

    // build the JSON object for this step
    jsonBuilder.append("{");
    jsonBuilder.append("\"idp\":\"").append(authenticatedIdPData.getIdpName()).append("\",");
    jsonBuilder
            .append("\"authenticator\":\"")
            .append(authenticatedIdPData.getAuthenticator().getApplicationAuthenticator()
                            .getName()).append("\"");
    // wrap up the JSON object
    jsonBuilder.append("}");
    jsonBuilder.append("]");

    sequenceConfig.setAuthenticatedIdPs(IdentityApplicationManagementUtil.getSignedJWT(jsonBuilder.toString(),
                    sequenceConfig.getApplicationConfig().getServiceProvider()));

    mappedAttrs = handleClaimMappings(context);
    String spRoleUri = getSpRoleClaimUri(sequenceConfig.getApplicationConfig());
    String roleAttr = mappedAttrs.get(spRoleUri);

    if (StringUtils.isNotBlank(roleAttr)) {
        String[] roles = roleAttr.split(Pattern.quote(FrameworkUtils.getMultiAttributeSeparator()));
        mappedAttrs.put(spRoleUri, getServiceProviderMappedUserRoles(sequenceConfig, Arrays.asList(roles)));
    }

    sequenceConfig.getAuthenticatedUser().setUserAttributes(FrameworkUtils.buildClaimMappings(mappedAttrs));

    if (StringUtils.isNotBlank(context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri())) {
        Map<String, String> unfilteredClaimValues =
                (Map<String, String>) context.getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);

        String subjectClaimUri = context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri().trim();
        String subjectClaimValue;
        if (unfilteredClaimValues != null) {
            subjectClaimValue = unfilteredClaimValues.get(subjectClaimUri);
        } else {
            subjectClaimValue = mappedAttrs.get(subjectClaimUri);
        }
        if (subjectClaimValue != null) {
            AuthenticatedUser authenticatedUser = sequenceConfig.getAuthenticatedUser();
            authenticatedUser.setAuthenticatedSubjectIdentifier(subjectClaimValue);

            if (log.isDebugEnabled()) {
                log.debug("Authenticated User: " +
                          sequenceConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier());
                log.debug("Authenticated User Tenant Domain: " + sequenceConfig.getAuthenticatedUser().getTenantDomain());
            }
        }
    }
}
 
Example 6
Source File: PostAuthAssociationHandlerTest.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * To get the authentication context and to call the handle method of the PostAuthAssociationHandler.
 *
 * @param sp1 Service Provider
 * @return relevant authentication context.
 * @throws FrameworkException Framework Exception.
 */
private AuthenticationContext processAndGetAuthenticationContext(ServiceProvider sp1, boolean
        withAuthenticatedUser, boolean isFederated, boolean withSpRoleMapping) throws FrameworkException {

    AuthenticationContext context = getAuthenticationContext(sp1);
    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.emptyMap(), sp1);
    sequenceConfig.getApplicationConfig().setAlwaysSendMappedLocalSubjectId(true);
    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("federated");
        authenticatedUser.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        authenticatedUser.setAuthenticatedSubjectIdentifier("federated");
        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);
    }

    if (withSpRoleMapping) {
        sequenceConfig.getApplicationConfig().getClaimMappings().put(FrameworkConstants.LOCAL_ROLE_CLAIM_URI,
                FrameworkConstants.LOCAL_ROLE_CLAIM_URI);
        sequenceConfig.getApplicationConfig().getServiceProvider().getClaimConfig().setLocalClaimDialect(true);
        sequenceConfig.getApplicationConfig().getRoleMappings().put(ORI_ROLE_1, SP_MAPPED_ROLE_1);
        sequenceConfig.getApplicationConfig().getRoleMappings().put(ORI_ROLE_2, SP_MAPPED_ROLE_2);
    }

    return context;
}
 
Example 7
Source File: PostAuthenticationMgtServiceTest.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
private void setUser(AuthenticationContext context, String userName) {

        AuthenticatedUser authenticatedUser = new AuthenticatedUser();
        authenticatedUser.setAuthenticatedSubjectIdentifier(userName);
        context.getSequenceConfig().setAuthenticatedUser(authenticatedUser);
    }
 
Example 8
Source File: AccessTokenGrantHandler.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    if (!super.validateGrant(tokReqMsgCtx)) {
        return false;
    } else {
        OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
        String username = null;
        String userTenantDomain = null;
        String clientId = oAuth2AccessTokenReqDTO.getClientId();
        String spTenantDomain = null;
        OAuthValidationResponse response;
        ServiceProvider serviceProvider;
        boolean authStatus = false;

        String accessToken = null;
        RequestParameter[] parameters = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getRequestParameters();

        for (RequestParameter parameter : parameters) {
            if (TOKEN_GRANT_PARAM.equals(parameter.getKey())) {
                if (parameter.getValue() != null && parameter.getValue().length > 0) {
                    accessToken = parameter.getValue()[0];
                }
            }
        }

        if (accessToken != null && !accessToken.isEmpty()) {
            try {
                response = tokenValidator.validateToken(accessToken);
            } catch (RemoteException e) {
                log.error("Failed to validate the OAuth token provided.", e);
                return false;
            }
            if (response != null && response.isValid()) {
                authStatus = true;
                username = response.getUserName() + "@" + response.getTenantDomain();
                userTenantDomain = MultitenantUtils.getTenantDomain(username);
                spTenantDomain = response.getTenantDomain();
            } else if (response != null && !response.isValid()) {
                throw new IdentityOAuth2Exception("Authentication failed for the provided access token");
            }
        }

        try {
            serviceProvider = OAuth2ServiceComponentHolder.getApplicationMgtService()
                    .getServiceProviderByClientId(clientId, "oauth2", spTenantDomain);
        } catch (IdentityApplicationManagementException var15) {
            throw new IdentityOAuth2Exception("Error occurred while retrieving OAuth2 application data for client id "
                    + clientId, var15);
        }

        if (!serviceProvider.isSaasApp() && !userTenantDomain.equals(spTenantDomain)) {
            if (log.isDebugEnabled()) {
                log.debug("Non-SaaS service provider tenant domain is not same as user tenant domain; "
                        + spTenantDomain + " != " + userTenantDomain);
            }

            return false;
        } else {
            String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
            username = tenantAwareUserName + "@" + userTenantDomain;
            if (authStatus) {
                if (!username.contains("/") && StringUtils.isNotBlank(UserCoreUtil.getDomainFromThreadLocal())) {
                    username = UserCoreUtil.getDomainFromThreadLocal() + "/" + username;
                }

                AuthenticatedUser user = OAuth2Util.getUserFromUserName(username);
                user.setAuthenticatedSubjectIdentifier(user.toString());
                tokReqMsgCtx.setAuthorizedUser(user);
                tokReqMsgCtx.setScope(oAuth2AccessTokenReqDTO.getScope());
                return authStatus;
            } else {
                throw new IdentityOAuth2Exception("Authentication failed for " + username);
            }
        }
    }
}
 
Example 9
Source File: DefaultRequestPathBasedSequenceHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected void handlePostAuthentication(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationContext context,
                                        AuthenticatedIdPData authenticatedIdPData) throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Handling Post Authentication tasks");
    }

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    Map<String, String> mappedAttrs;
    StringBuilder jsonBuilder = new StringBuilder();

    // build the authenticated idps JWT to send to the calling servlet.
    jsonBuilder.append("\"idps\":");
    jsonBuilder.append("[");

    // build the JSON object for this step
    jsonBuilder.append("{");
    jsonBuilder.append("\"idp\":\"").append(authenticatedIdPData.getIdpName()).append("\",");
    jsonBuilder
            .append("\"authenticator\":\"")
            .append(authenticatedIdPData.getAuthenticator().getApplicationAuthenticator()
                            .getName()).append("\"");
    // wrap up the JSON object
    jsonBuilder.append("}");
    jsonBuilder.append("]");

    sequenceConfig
            .setAuthenticatedIdPs(IdentityApplicationManagementUtil.getSignedJWT(jsonBuilder
                                                                                         .toString(), sequenceConfig.getApplicationConfig().getServiceProvider()));

    mappedAttrs = handleClaimMappings(context);
    String spRoleUri = getSpRoleClaimUri(sequenceConfig.getApplicationConfig());
    String roleAttr = mappedAttrs.get(spRoleUri);

    if (roleAttr != null && roleAttr.trim().length() > 0) {

        String[] roles = roleAttr.split(",");
        mappedAttrs.put(spRoleUri,
                        getServiceProviderMappedUserRoles(sequenceConfig, Arrays.asList(roles)));
    }

    sequenceConfig.getAuthenticatedUser().setUserAttributes(FrameworkUtils.buildClaimMappings(mappedAttrs));

    if (context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri() != null
        && context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri().trim()
                   .length() > 0) {
        Map<String, String> unfilteredClaimValues = (Map<String, String>) context
                .getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);

        String subjectValue = null;

        if (unfilteredClaimValues != null) {
            subjectValue = unfilteredClaimValues.get(context.getSequenceConfig()
                                                             .getApplicationConfig().getSubjectClaimUri().trim());
        } else {
            subjectValue = mappedAttrs.get(context.getSequenceConfig().getApplicationConfig()
                                                   .getSubjectClaimUri().trim());
        }
        if (subjectValue != null) {
            AuthenticatedUser authenticatedUser = sequenceConfig.getAuthenticatedUser();
            authenticatedUser.setAuthenticatedSubjectIdentifier(subjectValue);

            if (log.isDebugEnabled()) {
                log.debug("Authenticated User: " +
                          sequenceConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier());
                log.debug("Authenticated User Tenant Domain: " + sequenceConfig.getAuthenticatedUser().getTenantDomain());
            }
        }
    }
}