Java Code Examples for org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext#setSubject()

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext#setSubject() . 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 testResetAuthenticationContext() throws Exception {

    AuthenticationContext context = new AuthenticationContext();
    context.setSubject(new AuthenticatedUser());
    context.setStateInfo(mock(AuthenticatorStateInfo.class));
    context.setExternalIdP(mock(ExternalIdPConfig.class));

    Map<String, String> authenticatorProperties = new HashMap<>();
    authenticatorProperties.put("Prop1", "Value1");

    context.setAuthenticatorProperties(authenticatorProperties);
    context.setRetryCount(3);
    context.setRetrying(true);
    context.setCurrentAuthenticator("OIDCAuthenticator");

    stepBasedSequenceHandler.resetAuthenticationContext(context);

    assertResetContext(context);
}
 
Example 2
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 3
Source File: DefaultStepBasedSequenceHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
protected void resetAuthenticationContext(AuthenticationContext context) throws FrameworkException {
    context.setSubject(null);
    context.setStateInfo(null);
    context.setExternalIdP(null);
    context.setAuthenticatorProperties(new HashMap<String, String>());
    context.setRetryCount(0);
    context.setRetrying(false);
    context.setCurrentAuthenticator(null);
}
 
Example 4
Source File: MockUiAuthenticator.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {

    if (subjectCallback != null) {
        context.setSubject(subjectCallback.getAuthenticatedUser(context));
    }
}
 
Example 5
Source File: MockAuthenticator.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticatorFlowStatus process(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException, LogoutFailedException {

    if (subjectCallback != null) {
        context.setSubject(subjectCallback.getAuthenticatedUser(context));
    }
    return AuthenticatorFlowStatus.SUCCESS_COMPLETED;
}
 
Example 6
Source File: DefaultStepBasedSequenceHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected void resetAuthenticationContext(AuthenticationContext context)
        throws FrameworkException {

    context.setSubject(null);
    context.setStateInfo(null);
    context.setExternalIdP(null);
    context.setAuthenticatorProperties(new HashMap<String, String>());
    context.setRetryCount(0);
    context.setRetrying(false);
    context.setCurrentAuthenticator(null);
}
 
Example 7
Source File: FacebookAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void setSubject(AuthenticationContext context, Map<String, Object> jsonObject)
        throws ApplicationAuthenticatorException {
    String authenticatedUserId = (String) jsonObject.get(FacebookAuthenticatorConstants.DEFAULT_USER_IDENTIFIER);
    if (StringUtils.isEmpty(authenticatedUserId)) {
        throw new ApplicationAuthenticatorException("Authenticated user identifier is empty");
    }
    AuthenticatedUser authenticatedUser =
            AuthenticatedUser.createFederateAuthenticatedUserFromSubjectIdentifier(authenticatedUserId);
    context.setSubject(authenticatedUser);
}
 
Example 8
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 9
Source File: DefaultRequestCoordinator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected void findPreviousAuthenticatedSession(HttpServletRequest request,
                                                AuthenticationContext context) throws FrameworkException {

    // Get service provider chain
    SequenceConfig sequenceConfig = ConfigurationFacade.getInstance().getSequenceConfig(
            context.getRequestType(),
            request.getParameter(FrameworkConstants.RequestParams.ISSUER),
            context.getTenantDomain());

    Cookie cookie = FrameworkUtils.getAuthCookie(request);

    // if cookie exists user has previously authenticated
    if (cookie != null) {

        if (log.isDebugEnabled()) {
            log.debug(FrameworkConstants.COMMONAUTH_COOKIE
                      + " cookie is available with the value: " + cookie.getValue());
        }

        // get the authentication details from the cache
        SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(cookie
                                                                                          .getValue());

        if (sessionContext != null) {
            context.setSessionIdentifier(cookie.getValue());
            String appName = sequenceConfig.getApplicationConfig().getApplicationName();

            if (log.isDebugEnabled()) {
                log.debug("Service Provider is: " + appName);
            }

            SequenceConfig previousAuthenticatedSeq = sessionContext
                    .getAuthenticatedSequences().get(appName);

            if (previousAuthenticatedSeq != null) {

                if (log.isDebugEnabled()) {
                    log.debug("A previously authenticated sequence found for the SP: "
                              + appName);
                }

                context.setPreviousSessionFound(true);
                sequenceConfig = previousAuthenticatedSeq;
                AuthenticatedUser authenticatedUser = sequenceConfig.getAuthenticatedUser();
                String authenticatedUserTenantDomain = sequenceConfig.getAuthenticatedUser().getTenantDomain();

                if (authenticatedUser != null) {
                    // set the user for the current authentication/logout flow
                    context.setSubject(authenticatedUser);

                    if (log.isDebugEnabled()) {
                        log.debug("Already authenticated by username: " +
                                  authenticatedUser.getAuthenticatedSubjectIdentifier());
                    }

                    if (authenticatedUserTenantDomain != null) {
                        // set the user tenant domain for the current authentication/logout flow
                        context.setProperty("user-tenant-domain", authenticatedUserTenantDomain);

                        if (log.isDebugEnabled()) {
                            log.debug("Authenticated user tenant domain: " + authenticatedUserTenantDomain);
                        }
                    }
                }
            }

            context.setPreviousAuthenticatedIdPs(sessionContext.getAuthenticatedIdPs());
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Failed to find the SessionContext from the cache. Possible cache timeout.");
            }
        }
    }

    context.setServiceProviderName(sequenceConfig.getApplicationConfig().getApplicationName());

    // set the sequence for the current authentication/logout flow
    context.setSequenceConfig(sequenceConfig);
}
 
Example 10
Source File: SAMLSSOAuthenticator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response,
                                             AuthenticationContext context)
        throws AuthenticationFailedException {

    try {
        SAML2SSOManager saml2SSOManager = getSAML2SSOManagerInstance();
        saml2SSOManager.init(context.getTenantDomain(), context.getAuthenticatorProperties(),
                context.getExternalIdP().getIdentityProvider());
        saml2SSOManager.processResponse(request);
        Map<ClaimMapping, String> receivedClaims = (Map<ClaimMapping, String>) request
                .getSession(false).getAttribute("samlssoAttributes");

        String subject = null;
        String idpSubject = null;
        String isSubjectInClaimsProp = context.getAuthenticatorProperties().get(
                IdentityApplicationConstants.Authenticator.SAML2SSO.IS_USER_ID_IN_CLAIMS);
        if ("true".equalsIgnoreCase(isSubjectInClaimsProp)) {
            subject = FrameworkUtils.getFederatedSubjectFromClaims(
                    context.getExternalIdP().getIdentityProvider(), receivedClaims);
            if (subject == null) {
                log.warn("Subject claim could not be found amongst attribute statements. " +
                        "Defaulting to Name Identifier.");
            }
        }
        idpSubject = (String) request.getSession().getAttribute("username");
        if (subject == null) {
            subject = idpSubject;
        }
        if (subject == null) {
            throw new SAMLSSOException("Cannot find federated User Identifier");
        }

        Object sessionIndexObj = request.getSession(false).getAttribute(SSOConstants.IDP_SESSION);
        String nameQualifier = (String) request.getSession().getAttribute(SSOConstants.NAME_QUALIFIER);
        String spNameQualifier = (String) request.getSession().getAttribute(SSOConstants.SP_NAME_QUALIFIER);
        String sessionIndex = null;

        if (sessionIndexObj != null) {
            sessionIndex = (String) sessionIndexObj;
        }

        StateInfo stateInfoDO = new StateInfo();
        stateInfoDO.setSessionIndex(sessionIndex);
        stateInfoDO.setSubject(subject);
        stateInfoDO.setNameQualifier(nameQualifier);
        stateInfoDO.setSpNameQualifier(spNameQualifier);
        context.setStateInfo(stateInfoDO);

        AuthenticatedUser authenticatedUser =
                AuthenticatedUser.createFederateAuthenticatedUserFromSubjectIdentifier(subject);
        authenticatedUser.setUserAttributes(receivedClaims);
        context.setSubject(authenticatedUser);
    } catch (SAMLSSOException e) {
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}
 
Example 11
Source File: OAuthRequestPathAuthenticator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
protected void processAuthenticationResponse(HttpServletRequest request,
                                             HttpServletResponse response, AuthenticationContext context)
        throws AuthenticationFailedException {

    String headerValue = (String) request.getSession().getAttribute(AUTHORIZATION_HEADER_NAME);

    String token = null;
    if (headerValue != null) {
        token = headerValue.trim().split(" ")[1];
    } else {
        token = request.getParameter(ACCESS_TOKEN);
    }


    try {
        OAuth2TokenValidationService validationService = new OAuth2TokenValidationService();
        OAuth2TokenValidationRequestDTO validationReqDTO = new OAuth2TokenValidationRequestDTO();
        OAuth2AccessToken accessToken = validationReqDTO.new OAuth2AccessToken();
        accessToken.setIdentifier(token);
        accessToken.setTokenType("bearer");
        validationReqDTO.setAccessToken(accessToken);
        OAuth2TokenValidationResponseDTO validationResponse = validationService.validate(validationReqDTO);

        if (!validationResponse.isValid()) {
            log.error("RequestPath OAuth authentication failed");
            throw new AuthenticationFailedException("Authentication Failed");
        }

        String user = validationResponse.getAuthorizedUser();
        String tenantDomain = MultitenantUtils.getTenantDomain(user);

        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            user = MultitenantUtils.getTenantAwareUsername(user);
        }

        Map<String, Object> authProperties = context.getProperties();

        if (authProperties == null) {
            authProperties = new HashMap<String, Object>();
            context.setProperties(authProperties);
        }

        // TODO: user tenant domain has to be an attribute in the
        // AuthenticationContext
        authProperties.put("user-tenant-domain", tenantDomain);

        if (log.isDebugEnabled()) {
            log.debug("Authenticated user " + user);
        }

        context.setSubject(AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(user));
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}