Search in sources :

Example 1 with AuthenticatedUser

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticatorTest method testProcessWithLogoutFalse.

@Test
public void testProcessWithLogoutFalse() throws Exception {
    mockStatic(FederatedAuthenticatorUtil.class);
    mockStatic(SMSOTPUtils.class);
    mockStatic(FrameworkUtils.class);
    when(context.isLogoutRequest()).thenReturn(false);
    when(httpServletRequest.getParameter(SMSOTPConstants.MOBILE_NUMBER)).thenReturn("true");
    context.setTenantDomain("carbon.super");
    when((AuthenticatedUser) context.getProperty(SMSOTPConstants.AUTHENTICATED_USER)).thenReturn(AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier("admin"));
    FederatedAuthenticatorUtil.setUsernameFromFirstStep(context);
    when(SMSOTPUtils.isSMSOTPMandatory(context, SMSOTPConstants.AUTHENTICATOR_NAME)).thenReturn(true);
    when(SMSOTPUtils.getErrorPageFromXMLFile(context, SMSOTPConstants.AUTHENTICATOR_NAME)).thenReturn(SMSOTPConstants.ERROR_PAGE);
    when(SMSOTPUtils.isSendOTPDirectlyToMobile(context, SMSOTPConstants.AUTHENTICATOR_NAME)).thenReturn(false);
    when(FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier())).thenReturn(null);
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    Whitebox.invokeMethod(smsotpAuthenticator, "processSMSOTPFlow", context, httpServletRequest, httpServletResponse, false, "John@carbon.super", "", "carbon.super", SMSOTPConstants.ERROR_PAGE);
    verify(httpServletResponse).sendRedirect(captor.capture());
    AuthenticatorFlowStatus status = spy.process(httpServletRequest, httpServletResponse, context);
    Assert.assertTrue(captor.getValue().contains(SMSOTPConstants.SEND_OTP_DIRECTLY_DISABLE));
    Assert.assertEquals(status, AuthenticatorFlowStatus.INCOMPLETE);
}
Also used : Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 2 with AuthenticatedUser

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method processFirstStepOnly.

/**
 * In SMSOTP optional case proceed with first step only.It can be basic or federated.
 *
 * @param authenticatedUser the name of authenticatedUser
 * @param context           the AuthenticationContext
 */
private void processFirstStepOnly(AuthenticatedUser authenticatedUser, AuthenticationContext context) {
    if (log.isDebugEnabled()) {
        log.debug("Processing First step only. Skipping SMSOTP");
    }
    // the authentication flow happens with basic authentication.
    StepConfig stepConfig = context.getSequenceConfig().getStepMap().get(context.getCurrentStep() - 1);
    if (stepConfig.getAuthenticatedAutenticator().getApplicationAuthenticator() instanceof LocalApplicationAuthenticator) {
        if (log.isDebugEnabled()) {
            log.debug("Found local authenticator in previous step. Hence setting a local user");
        }
        FederatedAuthenticatorUtil.updateLocalAuthenticatedUserInStepConfig(context, authenticatedUser);
        context.setProperty(SMSOTPConstants.AUTHENTICATION, SMSOTPConstants.BASIC);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Found federated authenticator in previous step. Hence setting a local user");
        }
        FederatedAuthenticatorUtil.updateAuthenticatedUserInStepConfig(context, authenticatedUser);
        context.setProperty(SMSOTPConstants.AUTHENTICATION, SMSOTPConstants.FEDERETOR);
    }
}
Also used : StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) LocalApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator)

Example 3 with AuthenticatedUser

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method initiateAuthenticationRequest.

/**
 * Initiate the authentication request.
 */
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException {
    try {
        String username;
        AuthenticatedUser authenticatedUser;
        String mobileNumber;
        String tenantDomain = context.getTenantDomain();
        context.setProperty(SMSOTPConstants.AUTHENTICATION, SMSOTPConstants.AUTHENTICATOR_NAME);
        if (!tenantDomain.equals(SMSOTPConstants.SUPER_TENANT)) {
            IdentityHelperUtil.loadApplicationAuthenticationXMLFromRegistry(context, getName(), tenantDomain);
        }
        FederatedAuthenticatorUtil.setUsernameFromFirstStep(context);
        username = String.valueOf(context.getProperty(SMSOTPConstants.USER_NAME));
        authenticatedUser = (AuthenticatedUser) context.getProperty(SMSOTPConstants.AUTHENTICATED_USER);
        // find the authenticated user.
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug("Authentication failed: Could not find the authenticated user. ");
            }
            throw new AuthenticationFailedException("Authentication failed: Cannot proceed further without identifying the user. ");
        }
        boolean isSMSOTPMandatory = SMSOTPUtils.isSMSOTPMandatory(context, getName());
        boolean isUserExists = FederatedAuthenticatorUtil.isUserExistInUserStore(username);
        String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier());
        String errorPage = getErrorPage(context);
        // SMS OTP authentication is mandatory and user doesn't disable SMS OTP claim in user's profile.
        if (isSMSOTPMandatory) {
            if (log.isDebugEnabled()) {
                log.debug("SMS OTP is mandatory. Hence processing in mandatory path");
            }
            processSMSOTPMandatoryCase(context, request, response, queryParams, username, isUserExists);
        } else if (isUserExists && !SMSOTPUtils.isSMSOTPDisableForLocalUser(username, context, getName())) {
            if (context.isRetrying() && !Boolean.parseBoolean(request.getParameter(SMSOTPConstants.RESEND))) {
                checkStatusCode(response, context, queryParams, errorPage);
            } else {
                mobileNumber = getMobileNumber(request, response, context, username, tenantDomain, queryParams);
                if (StringUtils.isNotEmpty(mobileNumber)) {
                    proceedWithOTP(response, context, errorPage, mobileNumber, queryParams, username);
                }
            }
        } else {
            processFirstStepOnly(authenticatedUser, context);
        }
    } catch (SMSOTPException e) {
        throw new AuthenticationFailedException("Failed to get the parameters from authentication xml fie. ", e);
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Failed to get the user from User Store. ", e);
    }
}
Also used : AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) SMSOTPException(org.wso2.carbon.identity.authenticator.smsotp.exception.SMSOTPException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 4 with AuthenticatedUser

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser in project carbon-apimgt by wso2.

the class SystemScopesIssuer method configureForJWTGrant.

protected void configureForJWTGrant(OAuthTokenReqMessageContext tokReqMsgCtx) {
    SignedJWT signedJWT = null;
    JWTClaimsSet claimsSet = null;
    String[] roles = null;
    try {
        signedJWT = getSignedJWT(tokReqMsgCtx);
    } catch (IdentityOAuth2Exception e) {
        log.error("Couldn't retrieve signed JWT", e);
    }
    if (signedJWT != null) {
        claimsSet = getClaimSet(signedJWT);
    }
    String jwtIssuer = claimsSet != null ? claimsSet.getIssuer() : null;
    String tenantDomain = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain();
    try {
        identityProvider = IdentityProviderManager.getInstance().getIdPByName(jwtIssuer, tenantDomain);
        if (identityProvider != null) {
            if (StringUtils.equalsIgnoreCase(identityProvider.getIdentityProviderName(), "default")) {
                identityProvider = this.getResidentIDPForIssuer(tenantDomain, jwtIssuer);
                if (identityProvider == null) {
                    log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
                }
            }
        } else {
            log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
        }
    } catch (IdentityProviderManagementException | IdentityOAuth2Exception e) {
        log.error("Couldn't initiate identity provider instance", e);
    }
    try {
        roles = claimsSet != null ? claimsSet.getStringArrayClaim(identityProvider.getClaimConfig().getRoleClaimURI()) : null;
    } catch (ParseException e) {
        log.error("Couldn't retrieve roles:", e);
    }
    List<String> updatedRoles = new ArrayList<>();
    if (roles != null) {
        for (String role : roles) {
            String updatedRoleClaimValue = getUpdatedRoleClaimValue(identityProvider, role);
            if (updatedRoleClaimValue != null) {
                updatedRoles.add(updatedRoleClaimValue);
            } else {
                updatedRoles.add(role);
            }
        }
    }
    AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
    Map<ClaimMapping, String> userAttributes = user.getUserAttributes();
    String roleClaim = identityProvider.getClaimConfig().getRoleClaimURI();
    if (roleClaim != null) {
        userAttributes.put(ClaimMapping.build(roleClaim, roleClaim, null, false), updatedRoles.toString().replace(" ", ""));
        tokReqMsgCtx.addProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM, roleClaim);
    }
    user.setUserAttributes(userAttributes);
    tokReqMsgCtx.setAuthorizedUser(user);
}
Also used : SignedJWT(com.nimbusds.jwt.SignedJWT) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 5 with AuthenticatedUser

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser in project carbon-apimgt by wso2.

the class SystemScopesIssuer method getUserRoles.

/**
 * This method is used to get roles list of the user.
 *
 * @param authenticatedUser Authenticated user
 * @return roles list
 */
private String[] getUserRoles(AuthenticatedUser authenticatedUser) {
    String[] userRoles = null;
    String tenantDomain;
    String username;
    if (authenticatedUser.isFederatedUser()) {
        tenantDomain = MultitenantUtils.getTenantDomain(authenticatedUser.getAuthenticatedSubjectIdentifier());
        username = MultitenantUtils.getTenantAwareUsername(authenticatedUser.getAuthenticatedSubjectIdentifier());
    } else {
        tenantDomain = authenticatedUser.getTenantDomain();
        username = authenticatedUser.getUserName();
    }
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    RealmService realmService = getRealmService();
    try {
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        // If tenant Id is not set in the tokenReqContext, deriving it from username.
        if (tenantId == 0 || tenantId == -1) {
            tenantId = getTenantIdOfUser(username);
        }
        UserStoreManager userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        String endUsernameWithDomain = addDomainToName(username, userStoreDomain);
        userRoles = userStoreManager.getRoleListOfUser(endUsernameWithDomain);
    } catch (UserStoreException e) {
        // Log and return since we do not want to stop issuing the token in case of scope validation failures.
        log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
    }
    return userRoles;
}
Also used : RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Aggregations

AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)14 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 Test (org.testng.annotations.Test)4 AuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException)3 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)3 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)3 UserStoreException (org.wso2.carbon.user.api.UserStoreException)3 APIMgtDAOException (org.wso2.carbon.apimgt.api.APIMgtDAOException)2 SystemApplicationDAO (org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO)2 SystemApplicationDTO (org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO)2 AuthenticatorFlowStatus (org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus)2 IdentityOAuthAdminException (org.wso2.carbon.identity.oauth.IdentityOAuthAdminException)2 OAuthConsumerAppDTO (org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 ParseException (java.text.ParseException)1 Cache (javax.cache.Cache)1 Before (org.junit.Before)1 Matchers.anyString (org.mockito.Matchers.anyString)1 Assertion (org.opensaml.saml.saml2.core.Assertion)1