Search in sources :

Example 11 with AuthenticationResult

use of org.wso2.carbon.user.core.common.AuthenticationResult in project identity-inbound-auth-oauth by wso2-extensions.

the class PasswordGrantHandler method validateUserCredentials.

private AuthenticatedUser validateUserCredentials(OAuth2AccessTokenReqDTO tokenReq, ServiceProvider serviceProvider) throws IdentityOAuth2Exception {
    boolean isPublishPasswordGrantLoginEnabled = Boolean.parseBoolean(IdentityUtil.getProperty(PUBLISH_PASSWORD_GRANT_LOGIN));
    try {
        // Get the user store preference order supplier.
        UserStorePreferenceOrderSupplier<List<String>> userStorePreferenceOrderSupplier = FrameworkUtils.getUserStorePreferenceOrderSupplier(null, serviceProvider);
        UserMgtContext userMgtContext = new UserMgtContext();
        userMgtContext.setUserStorePreferenceOrderSupplier(userStorePreferenceOrderSupplier);
        if (userStorePreferenceOrderSupplier != null) {
            UserCoreUtil.setUserMgtContextInThreadLocal(userMgtContext);
            if (log.isDebugEnabled()) {
                log.debug("UserMgtContext had been set as the thread local.");
            }
        }
        String username = tokenReq.getResourceOwnerUsername();
        if (!IdentityUtil.isEmailUsernameValidationDisabled()) {
            FrameworkUtils.validateUsername(username);
            username = FrameworkUtils.preprocessUsername(username, serviceProvider);
        }
        String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
        String userTenantDomain = MultitenantUtils.getTenantDomain(username);
        ResolvedUserResult resolvedUserResult = FrameworkUtils.processMultiAttributeLoginIdentification(tenantAwareUserName, userTenantDomain);
        String userId = null;
        if (resolvedUserResult != null && ResolvedUserResult.UserResolvedStatus.SUCCESS.equals(resolvedUserResult.getResolvedStatus())) {
            tenantAwareUserName = resolvedUserResult.getUser().getUsername();
            userId = resolvedUserResult.getUser().getUserID();
            tokenReq.setResourceOwnerUsername(tenantAwareUserName + "@" + userTenantDomain);
        }
        AbstractUserStoreManager userStoreManager = getUserStoreManager(userTenantDomain);
        AuthenticationResult authenticationResult;
        if (userId != null) {
            authenticationResult = userStoreManager.authenticateWithID(userId, tokenReq.getResourceOwnerPassword());
        } else {
            authenticationResult = userStoreManager.authenticateWithID(UserCoreClaimConstants.USERNAME_CLAIM_URI, tenantAwareUserName, tokenReq.getResourceOwnerPassword(), UserCoreConstants.DEFAULT_PROFILE);
        }
        boolean authenticated = AuthenticationResult.AuthenticationStatus.SUCCESS == authenticationResult.getAuthenticationStatus() && authenticationResult.getAuthenticatedUser().isPresent();
        if (log.isDebugEnabled()) {
            log.debug("user " + tokenReq.getResourceOwnerUsername() + " authenticated: " + authenticated);
        }
        if (authenticated) {
            AuthenticatedUser authenticatedUser = new AuthenticatedUser(authenticationResult.getAuthenticatedUser().get());
            if (isPublishPasswordGrantLoginEnabled) {
                publishAuthenticationData(tokenReq, true, serviceProvider, authenticatedUser);
            }
            return authenticatedUser;
        } else {
            if (isPublishPasswordGrantLoginEnabled) {
                publishAuthenticationData(tokenReq, false, serviceProvider);
            }
            if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(MultitenantUtils.getTenantDomain(tokenReq.getResourceOwnerUsername()))) {
                throw new IdentityOAuth2Exception("Authentication failed for " + tenantAwareUserName);
            }
            username = tokenReq.getResourceOwnerUsername();
            if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
                // For tenant qualified urls, no need to send fully qualified username in response.
                username = tenantAwareUserName;
            }
            throw new IdentityOAuth2Exception("Authentication failed for " + username);
        }
    } catch (UserStoreClientException e) {
        if (isPublishPasswordGrantLoginEnabled) {
            publishAuthenticationData(tokenReq, false, serviceProvider);
        }
        String message = e.getMessage();
        if (StringUtils.isNotBlank(e.getErrorCode())) {
            message = e.getErrorCode() + " " + e.getMessage();
        }
        throw new IdentityOAuth2Exception(message, e);
    } catch (UserStoreException e) {
        if (isPublishPasswordGrantLoginEnabled) {
            publishAuthenticationData(tokenReq, false, serviceProvider);
        }
        String message = e.getMessage();
        // Sometimes client exceptions are wrapped in the super class.
        // Therefore, checking for possible client exception.
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause instanceof UserStoreClientException) {
            message = rootCause.getMessage();
            String errorCode = ((UserStoreClientException) rootCause).getErrorCode();
            if (StringUtils.isNotBlank(errorCode)) {
                message = errorCode + " " + message;
            }
        }
        if (e.getCause() instanceof IdentityException) {
            IdentityException identityException = (IdentityException) (e.getCause());
            // Set error code to message if available.
            if (StringUtils.isNotBlank(identityException.getErrorCode())) {
                message = identityException.getErrorCode() + " " + e.getMessage();
            }
        }
        throw new IdentityOAuth2Exception(message, e);
    } catch (AuthenticationFailedException e) {
        String message = "Authentication failed for the user: " + tokenReq.getResourceOwnerUsername();
        if (log.isDebugEnabled()) {
            log.debug(message, e);
        }
        throw new IdentityOAuth2Exception(message);
    } finally {
        UserCoreUtil.removeUserMgtContextInThreadLocal();
        if (log.isDebugEnabled()) {
            log.debug("UserMgtContext had been remove from the thread local.");
        }
    }
}
Also used : UserMgtContext(org.wso2.carbon.user.core.model.UserMgtContext) UserStoreClientException(org.wso2.carbon.user.core.UserStoreClientException) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) IdentityException(org.wso2.carbon.identity.base.IdentityException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AuthenticationResult(org.wso2.carbon.user.core.common.AuthenticationResult) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) UserStoreException(org.wso2.carbon.user.api.UserStoreException) List(java.util.List) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) ResolvedUserResult(org.wso2.carbon.identity.multi.attribute.login.mgt.ResolvedUserResult)

Example 12 with AuthenticationResult

use of org.wso2.carbon.user.core.common.AuthenticationResult in project identity-inbound-auth-oauth by wso2-extensions.

the class BasicAuthClientAuthenticatorTest method testAuthenticateClient.

@Test(dataProvider = "testClientAuthnData")
public void testAuthenticateClient(String headerName, String headerValue, HashMap<String, List> bodyContent, Object oAuthClientAuthnContextObj, boolean isAuthenticated, boolean authenticationResult) throws Exception {
    OAuthClientAuthnContext oAuthClientAuthnContext = (OAuthClientAuthnContext) oAuthClientAuthnContextObj;
    HttpServletRequest httpServletRequest = PowerMockito.mock(HttpServletRequest.class);
    PowerMockito.mockStatic(OAuth2Util.class);
    PowerMockito.when(OAuth2Util.authenticateClient(Matchers.anyString(), Matchers.anyString())).thenReturn(isAuthenticated);
    PowerMockito.when(httpServletRequest.getHeader(headerName)).thenReturn(headerValue);
    assertEquals(basicAuthClientAuthenticator.authenticateClient(httpServletRequest, bodyContent, oAuthClientAuthnContext), authenticationResult, "Expected client authentication result was not " + "received");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthClientAuthnContext(org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext) Test(org.testng.annotations.Test) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 13 with AuthenticationResult

use of org.wso2.carbon.user.core.common.AuthenticationResult in project identity-inbound-auth-oauth by wso2-extensions.

the class PasswordGrantHandlerTest method testValidateGrantForException.

@Test(dataProvider = "GetValidateGrantForExceptionDataProvider", expectedExceptions = IdentityOAuth2Exception.class)
public void testValidateGrantForException(String tenantDomain, boolean authenticated, boolean isSaas, Exception e, String reasonForError) throws Exception {
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(serverConfiguration);
    when(serverConfiguration.getIdentityOauthTokenIssuer()).thenReturn(oauthIssuer);
    mockStatic(MultitenantUtils.class);
    when(MultitenantUtils.getTenantDomain(anyString())).thenReturn(tenantDomain);
    when(tokReqMsgCtx.getOauth2AccessTokenReqDTO()).thenReturn(oAuth2AccessTokenReqDTO);
    when(oAuth2AccessTokenReqDTO.getResourceOwnerUsername()).thenReturn("username");
    when(oAuth2AccessTokenReqDTO.getClientId()).thenReturn(CLIENT_ID);
    when(oAuth2AccessTokenReqDTO.getTenantDomain()).thenReturn("carbon.super");
    when(oAuth2AccessTokenReqDTO.getResourceOwnerPassword()).thenReturn("password");
    mockStatic(IdentityUtil.class);
    when(IdentityUtil.extractDomainFromName(anyString())).thenReturn(PRIMARY_DEFAULT_DOMAIN_NAME);
    when(MultitenantUtils.getTenantAwareUsername(anyString())).thenReturn("username");
    mockStatic(OAuth2ServiceComponentHolder.class);
    when(OAuth2ServiceComponentHolder.getApplicationMgtService()).thenReturn(applicationManagementService);
    OAuthComponentServiceHolder.getInstance().setRealmService(realmService);
    mockStatic(FrameworkUtils.class);
    ResolvedUserResult resolvedUserResult = new ResolvedUserResult(ResolvedUserResult.UserResolvedStatus.FAIL);
    when(FrameworkUtils.processMultiAttributeLoginIdentification(anyString(), anyString())).thenReturn(resolvedUserResult);
    if (e instanceof IdentityApplicationManagementException) {
        when(applicationManagementService.getServiceProviderByClientId(anyString(), anyString(), anyString())).thenThrow(e);
    } else {
        when(applicationManagementService.getServiceProviderByClientId(anyString(), anyString(), anyString())).thenReturn(serviceProvider);
        when(serviceProvider.isSaasApp()).thenReturn(isSaas);
        when(serviceProvider.getLocalAndOutBoundAuthenticationConfig()).thenReturn(localAndOutboundAuthenticationConfig);
    }
    when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm);
    if (e instanceof UserStoreException) {
        when(userRealm.getUserStoreManager()).thenThrow(e);
    } else {
        when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    }
    AuthenticationResult authenticationResult;
    if (authenticated) {
        org.wso2.carbon.user.core.common.User userObj = new org.wso2.carbon.user.core.common.User("c2de9b28-f258-4df0-ba29-f4803e4e821a", "username", "username");
        userObj.setTenantDomain("dummyTenantDomain");
        resolvedUserResult.setUser(userObj);
        authenticationResult = new AuthenticationResult(AuthenticationResult.AuthenticationStatus.SUCCESS);
        authenticationResult.setAuthenticatedUser(userObj);
    } else {
        authenticationResult = new AuthenticationResult(AuthenticationResult.AuthenticationStatus.FAIL);
    }
    when(userStoreManager.authenticateWithID(eq(UserCoreClaimConstants.USERNAME_CLAIM_URI), anyString(), anyObject(), eq(UserCoreConstants.DEFAULT_PROFILE))).thenReturn(authenticationResult);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantIdOfUser(anyString())).thenReturn(1);
    PasswordGrantHandler passwordGrantHandler = new PasswordGrantHandler();
    passwordGrantHandler.validateGrant(tokReqMsgCtx);
    fail("Password grant validation should fail with the reason " + reasonForError);
}
Also used : IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) AuthenticationResult(org.wso2.carbon.user.core.common.AuthenticationResult) UserStoreException(org.wso2.carbon.user.core.UserStoreException) ResolvedUserResult(org.wso2.carbon.identity.multi.attribute.login.mgt.ResolvedUserResult) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 14 with AuthenticationResult

use of org.wso2.carbon.user.core.common.AuthenticationResult in project identity-inbound-auth-oauth by wso2-extensions.

the class PasswordGrantHandlerTest method testValidateGrant.

@Test(dataProvider = "ValidateGrantDataProvider")
public void testValidateGrant(String username, boolean isSaas) throws Exception {
    when(tokReqMsgCtx.getOauth2AccessTokenReqDTO()).thenReturn(oAuth2AccessTokenReqDTO);
    when(oAuth2AccessTokenReqDTO.getResourceOwnerUsername()).thenReturn(username + "wso2.com");
    when(oAuth2AccessTokenReqDTO.getClientId()).thenReturn(CLIENT_ID);
    when(oAuth2AccessTokenReqDTO.getTenantDomain()).thenReturn("wso2.com");
    when(oAuth2AccessTokenReqDTO.getResourceOwnerPassword()).thenReturn("randomPassword");
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(serverConfiguration);
    when(serverConfiguration.getIdentityOauthTokenIssuer()).thenReturn(oauthIssuer);
    mockStatic(MultitenantUtils.class);
    when(MultitenantUtils.getTenantDomain(anyString())).thenReturn("wso2.com");
    when(MultitenantUtils.getTenantAwareUsername(anyString())).thenReturn(username);
    mockStatic(OAuth2ServiceComponentHolder.class);
    when(OAuth2ServiceComponentHolder.getApplicationMgtService()).thenReturn(applicationManagementService);
    mockStatic(FrameworkUtils.class);
    ResolvedUserResult resolvedUserResult = new ResolvedUserResult(ResolvedUserResult.UserResolvedStatus.FAIL);
    when(FrameworkUtils.processMultiAttributeLoginIdentification(anyString(), anyString())).thenReturn(resolvedUserResult);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantIdOfUser(anyString())).thenReturn(1);
    mockStatic(UserCoreUtil.class);
    when(UserCoreUtil.getDomainFromThreadLocal()).thenReturn("DOMAIN");
    when(UserCoreUtil.removeDomainFromName(anyString())).thenReturn("wso2.com");
    mockStatic(OAuthComponentServiceHolder.class);
    when(OAuthComponentServiceHolder.getInstance()).thenReturn(oAuthComponentServiceHolder);
    when(oAuthComponentServiceHolder.getRealmService()).thenReturn(realmService);
    when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm);
    when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    org.wso2.carbon.user.core.common.User userObj = new org.wso2.carbon.user.core.common.User("c2de9b28-f258-4df0-ba29-f4803e4e821a", username, username);
    userObj.setTenantDomain("dummyTenantDomain");
    resolvedUserResult.setUser(userObj);
    AuthenticationResult authenticationResult = new AuthenticationResult(AuthenticationResult.AuthenticationStatus.SUCCESS);
    authenticationResult.setAuthenticatedUser(userObj);
    when(userStoreManager.authenticateWithID(eq(UserCoreClaimConstants.USERNAME_CLAIM_URI), anyString(), anyObject(), eq(UserCoreConstants.DEFAULT_PROFILE))).thenReturn(authenticationResult);
    when(applicationManagementService.getServiceProviderByClientId(anyString(), anyString(), anyString())).thenReturn(serviceProvider);
    when(serviceProvider.isSaasApp()).thenReturn(isSaas);
    when(serviceProvider.getLocalAndOutBoundAuthenticationConfig()).thenReturn(localAndOutboundAuthenticationConfig);
    when(localAndOutboundAuthenticationConfig.isUseUserstoreDomainInLocalSubjectIdentifier()).thenReturn(true);
    when(localAndOutboundAuthenticationConfig.isUseTenantDomainInLocalSubjectIdentifier()).thenReturn(true);
    PasswordGrantHandler passwordGrantHandler = new PasswordGrantHandler();
    boolean isValid = passwordGrantHandler.validateGrant(tokReqMsgCtx);
    assertTrue(isValid, "Password grant validation should be successful");
}
Also used : ResolvedUserResult(org.wso2.carbon.identity.multi.attribute.login.mgt.ResolvedUserResult) AuthenticationResult(org.wso2.carbon.user.core.common.AuthenticationResult) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 15 with AuthenticationResult

use of org.wso2.carbon.user.core.common.AuthenticationResult in project carbon-identity-framework by wso2.

the class DefaultAuthenticationRequestHandlerTest method testPopulateErrorInformation.

@Test(dataProvider = "errorInfoDataProvider")
public void testPopulateErrorInformation(String errorCode, String errorMessage, String errorUri, String requestType) throws Exception {
    AuthenticationResult authenticationResult = new AuthenticationResult();
    doReturn(authenticationResult).when(request).getAttribute(FrameworkConstants.RequestAttribute.AUTH_RESULT);
    // Populate the context with error details
    AuthenticationContext context = new AuthenticationContext();
    context.setProperty(FrameworkConstants.AUTH_ERROR_CODE, errorCode);
    context.setProperty(FrameworkConstants.AUTH_ERROR_MSG, errorMessage);
    context.setProperty(FrameworkConstants.AUTH_ERROR_URI, errorUri);
    // request type is does not cache authentication result
    context.setRequestType(requestType);
    response = spy(new CommonAuthResponseWrapper(response));
    // if request type caches authentication result we need to mock required dependent objects
    AuthenticationResultCacheEntry cacheEntry = spy(new AuthenticationResultCacheEntry());
    when(cacheEntry.getResult()).thenReturn(authenticationResult);
    mockStatic(FrameworkUtils.class);
    when(FrameworkUtils.getAuthenticationResultFromCache(anyString())).thenReturn(cacheEntry);
    authenticationRequestHandler.populateErrorInformation(request, response, context);
    // Assert stuff
    AuthenticationResult modifiedAuthenticationResult = (AuthenticationResult) request.getAttribute(FrameworkConstants.RequestAttribute.AUTH_RESULT);
    assertNotNull(modifiedAuthenticationResult);
    assertEquals(modifiedAuthenticationResult.getProperty(FrameworkConstants.AUTH_ERROR_CODE), errorCode);
    assertEquals(modifiedAuthenticationResult.getProperty(FrameworkConstants.AUTH_ERROR_MSG), errorMessage);
    assertEquals(modifiedAuthenticationResult.getProperty(FrameworkConstants.AUTH_ERROR_URI), errorUri);
}
Also used : AuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper) AuthenticationResultCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationResultCacheEntry) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult) Test(org.testng.annotations.Test) PostAuthenticationMgtServiceTest(org.wso2.carbon.identity.application.authentication.framework.services.PostAuthenticationMgtServiceTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

AuthenticationResult (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 Test (org.testng.annotations.Test)8 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)7 AuthenticationResult (org.wso2.carbon.user.core.common.AuthenticationResult)6 AuthenticationResultCacheEntry (org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationResultCacheEntry)5 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)5 HashMap (java.util.HashMap)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 AfterTest (org.testng.annotations.AfterTest)4 BeforeTest (org.testng.annotations.BeforeTest)4 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)3 Response (javax.ws.rs.core.Response)3 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)3 Matchers.anyString (org.mockito.Matchers.anyString)3 CommonAuthResponseWrapper (org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)3 AbstractIdentityUserOperationEventListener (org.wso2.carbon.identity.core.AbstractIdentityUserOperationEventListener)3 ResolvedUserResult (org.wso2.carbon.identity.multi.attribute.login.mgt.ResolvedUserResult)3