Search in sources :

Example 21 with AuthenticationResult

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

the class OAuth2AuthzEndpointTest method testAuthorizeForAuthenticationResponse.

@Test(dataProvider = "provideAuthenticatedData", groups = "testWithConnection")
public void testAuthorizeForAuthenticationResponse(boolean isResultInRequest, boolean isAuthenticated, Map<ClaimMapping, String> attributes, String errorCode, String errorMsg, String errorUri, Set<String> scopes, String responseMode, String redirectUri, int expected) throws Exception {
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE);
    when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry);
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    AuthenticationResult result = setAuthenticationResult(isAuthenticated, attributes, errorCode, errorMsg, errorUri);
    AuthenticationResult resultInRequest = null;
    AuthenticationResultCacheEntry authResultCacheEntry = null;
    if (isResultInRequest) {
        resultInRequest = result;
    } else {
        authResultCacheEntry = new AuthenticationResultCacheEntry();
        authResultCacheEntry.setResult(result);
    }
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, SESSION_DATA_KEY_VALUE);
    requestAttributes.put(FrameworkConstants.RequestAttribute.AUTH_RESULT, resultInRequest);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    spy(FrameworkUtils.class);
    doReturn(requestCoordinator).when(FrameworkUtils.class, "getRequestCoordinator");
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    spy(IdentityUtil.class);
    doReturn("https://localhost:9443/carbon").when(IdentityUtil.class, "getServerURL", anyString(), anyBoolean(), anyBoolean());
    OAuth2Parameters oAuth2Params = setOAuth2Parameters(scopes, APP_NAME, responseMode, redirectUri);
    oAuth2Params.setClientId(CLIENT_ID_VALUE);
    oAuth2Params.setState(STATE);
    when(loginCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
    when(loginCacheEntry.getLoggedInUser()).thenReturn(result.getSubject());
    mockOAuthServerConfiguration();
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    spy(FrameworkUtils.class);
    doReturn("sample").when(FrameworkUtils.class, "resolveUserIdFromUsername", anyInt(), anyString(), anyString());
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    try (Connection connection = getConnection()) {
        mockStatic(IdentityDatabaseUtil.class);
        when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
        mockStatic(OpenIDConnectUserRPStore.class);
        when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
        when(openIDConnectUserRPStore.hasUserApproved(any(AuthenticatedUser.class), anyString(), anyString())).thenReturn(true);
        mockEndpointUtil(false);
        when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
        mockApplicationManagementService();
        mockEndpointUtil(false);
        when(oAuth2Service.handleAuthenticationFailure(oAuth2Params)).thenReturn(oAuthErrorDTO);
        when(oAuth2ScopeService.hasUserProvidedConsentForAllRequestedScopes(anyString(), anyString(), anyInt(), anyList())).thenReturn(true);
        mockServiceURLBuilder();
        Response response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
        assertEquals(response.getStatus(), expected, "Unexpected HTTP response status");
        if (!isAuthenticated) {
            String expectedState = "name=\"" + OAuthConstants.OAuth20Params.STATE + "\" value=\"" + STATE + "\"";
            assertTrue(response.getEntity().toString().contains(expectedState));
        }
    }
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Connection(java.sql.Connection) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) 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) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 22 with AuthenticationResult

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

the class OAuth2AuthzEndpointTest method setAuthenticationResult.

private AuthenticationResult setAuthenticationResult(boolean isAuthenticated, Map<ClaimMapping, String> attributes, String errorCode, String errorMsg, String errorUri) {
    AuthenticationResult authResult = new AuthenticationResult();
    authResult.setAuthenticated(isAuthenticated);
    if (!isAuthenticated) {
        authResult.addProperty(FrameworkConstants.AUTH_ERROR_CODE, errorCode);
        authResult.addProperty(FrameworkConstants.AUTH_ERROR_MSG, errorMsg);
        authResult.addProperty(FrameworkConstants.AUTH_ERROR_URI, errorUri);
    }
    AuthenticatedUser subject = new AuthenticatedUser();
    subject.setAuthenticatedSubjectIdentifier(USERNAME);
    subject.setUserName(USERNAME);
    subject.setUserAttributes(attributes);
    subject.setUserId(USER_ID);
    authResult.setSubject(subject);
    return authResult;
}
Also used : AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult)

Example 23 with AuthenticationResult

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

the class OAuth2AuthzEndpointTest method testManageOIDCSessionState.

@Test(dataProvider = "provideOidcSessionData", groups = "testWithConnection")
public void testManageOIDCSessionState(Object cookieObject, Object sessionStateObject, String callbackUrl, String responseMode, int expectedStatus, String expectedResult) throws Exception {
    Cookie opBrowserStateCookie = (Cookie) cookieObject;
    Cookie newOpBrowserStateCookie = new Cookie("opbs", "f6454r678776gffdgdsfafa");
    OIDCSessionState previousSessionState = (OIDCSessionState) sessionStateObject;
    AuthenticationResult result = setAuthenticationResult(true, null, null, null, null);
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
    requestParams.put(OAuthConstants.OAuth20Params.PROMPT, new String[] { OAuthConstants.Prompt.LOGIN });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, SESSION_DATA_KEY_VALUE);
    requestAttributes.put(FrameworkConstants.RequestAttribute.AUTH_RESULT, result);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), APP_NAME, responseMode, APP_REDIRECT_URL);
    oAuth2Params.setClientId(CLIENT_ID_VALUE);
    oAuth2Params.setPrompt(OAuthConstants.Prompt.LOGIN);
    mockOAuthServerConfiguration();
    mockEndpointUtil(false);
    when(oAuthServerConfiguration.getOpenIDConnectSkipeUserConsentConfig()).thenReturn(true);
    OAuth2AuthorizeRespDTO authzRespDTO = new OAuth2AuthorizeRespDTO();
    authzRespDTO.setCallbackURI(callbackUrl);
    when(oAuth2Service.authorize(any(OAuth2AuthorizeReqDTO.class))).thenReturn(authzRespDTO);
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    mockStatic(OIDCSessionManagementUtil.class);
    when(OIDCSessionManagementUtil.getOPBrowserStateCookie(any(HttpServletRequest.class))).thenReturn(opBrowserStateCookie);
    when(OIDCSessionManagementUtil.addOPBrowserStateCookie(any(HttpServletResponse.class))).thenReturn(newOpBrowserStateCookie);
    when(OIDCSessionManagementUtil.addOPBrowserStateCookie(any(HttpServletResponse.class), any(HttpServletRequest.class), any(String.class), any(String.class))).thenReturn(newOpBrowserStateCookie);
    when(OIDCSessionManagementUtil.getSessionManager()).thenReturn(oidcSessionManager);
    when(oidcSessionManager.getOIDCSessionState(anyString(), anyString())).thenReturn(previousSessionState);
    when(OIDCSessionManagementUtil.getSessionStateParam(anyString(), anyString(), anyString())).thenReturn("sessionStateValue");
    when(OIDCSessionManagementUtil.addSessionStateToURL(anyString(), anyString(), anyString())).thenCallRealMethod();
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE);
    when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry);
    when(loginCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
    when(loginCacheEntry.getLoggedInUser()).thenReturn(result.getSubject());
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    mockStatic(OpenIDConnectUserRPStore.class);
    when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
    when(openIDConnectUserRPStore.hasUserApproved(any(AuthenticatedUser.class), anyString(), anyString())).thenReturn(true);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    mockApplicationManagementService();
    spy(FrameworkUtils.class);
    doReturn("sample").when(FrameworkUtils.class, "resolveUserIdFromUsername", anyInt(), anyString(), anyString());
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    spy(IdentityTenantUtil.class);
    doReturn(MultitenantConstants.SUPER_TENANT_ID).when(IdentityTenantUtil.class, "getTenantId", anyString());
    doReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME).when(IdentityTenantUtil.class, "getTenantDomain", anyInt());
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Authorization response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
    MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
    assertNotNull(responseMetadata, "Response metadata is null");
    if (response.getStatus() != HttpServletResponse.SC_OK) {
        assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
        String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
        assertTrue(location.contains(expectedResult), "Expected redirect URL is not returned");
    } else {
        assertTrue(response.getEntity().toString().contains(expectedResult), "Expected redirect URL is not returned");
    }
}
Also used : Cookie(javax.servlet.http.Cookie) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) HttpServletResponse(javax.servlet.http.HttpServletResponse) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) OIDCSessionState(org.wso2.carbon.identity.oidc.session.OIDCSessionState) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 24 with AuthenticationResult

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

the class OAuth2AuthzEndpointTest method testDoUserAuthz.

@Test(dataProvider = "provideDataForUserAuthz", groups = "testWithConnection")
public void testDoUserAuthz(String prompt, String idTokenHint, boolean hasUserApproved, boolean skipConsent, boolean idTokenHintValid, String loggedInUser, String idTokenHintSubject, String errorCode) throws Exception {
    AuthenticationResult result = setAuthenticationResult(true, null, null, null, null);
    result.getSubject().setAuthenticatedSubjectIdentifier(loggedInUser);
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, SESSION_DATA_KEY_VALUE);
    requestAttributes.put(FrameworkConstants.RequestAttribute.AUTH_RESULT, result);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<String>(), APP_NAME, null, APP_REDIRECT_URL);
    oAuth2Params.setClientId(CLIENT_ID_VALUE);
    oAuth2Params.setPrompt(prompt);
    oAuth2Params.setIDTokenHint(idTokenHint);
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE);
    when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry);
    when(loginCacheEntry.getLoggedInUser()).thenReturn(result.getSubject());
    when(loginCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
    mockEndpointUtil(false);
    when(oAuth2ScopeService.hasUserProvidedConsentForAllRequestedScopes(anyString(), anyString(), anyInt(), anyList())).thenReturn(hasUserApproved);
    mockOAuthServerConfiguration();
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    mockStatic(OpenIDConnectUserRPStore.class);
    when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
    when(openIDConnectUserRPStore.hasUserApproved(any(AuthenticatedUser.class), anyString(), anyString())).thenReturn(hasUserApproved);
    spy(OAuth2Util.class);
    doReturn(idTokenHintValid).when(OAuth2Util.class, "validateIdToken", anyString());
    mockStatic(SignedJWT.class);
    if ("invalid".equals(idTokenHint)) {
        when(SignedJWT.parse(anyString())).thenThrow(new ParseException("error", 1));
    } else {
        when(SignedJWT.parse(anyString())).thenReturn(signedJWT);
    }
    JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder();
    jwtClaimsSetBuilder.subject(idTokenHintSubject);
    JWTClaimsSet jwtClaimsSet = jwtClaimsSetBuilder.build();
    when(signedJWT.getJWTClaimsSet()).thenReturn(jwtClaimsSet);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    mockApplicationManagementService();
    spy(FrameworkUtils.class);
    doReturn("sample").when(FrameworkUtils.class, "resolveUserIdFromUsername", anyInt(), anyString(), anyString());
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    spy(IdentityTenantUtil.class);
    doReturn(MultitenantConstants.SUPER_TENANT_ID).when(IdentityTenantUtil.class, "getTenantId", anyString());
    doReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME).when(IdentityTenantUtil.class, "getTenantDomain", anyInt());
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Authorization response is null");
    assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND, "Unexpected HTTP response status");
    if (errorCode != null) {
        MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
        assertNotNull(responseMetadata, "Response metadata is null");
        assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
        String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
        assertTrue(location.contains(errorCode), "Expected error code not found in URL");
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) ParseException(java.text.ParseException) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 25 with AuthenticationResult

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

the class OAuth2AuthzEndpoint method handleSuccessfulAuthentication.

private Response handleSuccessfulAuthentication(OAuthMessage oAuthMessage, OAuth2Parameters oauth2Params, AuthenticationResult authenticationResult) throws OAuthSystemException, URISyntaxException, ConsentHandlingFailedException {
    boolean isOIDCRequest = OAuth2Util.isOIDCAuthzRequest(oauth2Params.getScopes());
    AuthenticatedUser authenticatedUser = authenticationResult.getSubject();
    if (authenticatedUser.getUserAttributes() != null) {
        authenticatedUser.setUserAttributes(new ConcurrentHashMap<>(authenticatedUser.getUserAttributes()));
    }
    addToAuthenticationResultDetailsToOAuthMessage(oAuthMessage, authenticationResult, authenticatedUser);
    OIDCSessionState sessionState = new OIDCSessionState();
    String redirectURL = null;
    try {
        redirectURL = doUserAuthorization(oAuthMessage, oAuthMessage.getSessionDataKeyFromLogin(), sessionState);
    } catch (OAuthProblemException ex) {
        if (StringUtils.equals(oauth2Params.getResponseMode(), RESPONSE_MODE_FORM_POST)) {
            return handleFailedState(oAuthMessage, oauth2Params, ex);
        } else {
            redirectURL = EndpointUtil.getErrorRedirectURL(ex, oauth2Params);
        }
    }
    if (isFormPostResponseMode(oAuthMessage, redirectURL)) {
        return handleFormPostMode(oAuthMessage, oauth2Params, redirectURL, isOIDCRequest, sessionState);
    }
    if (isOIDCRequest) {
        redirectURL = manageOIDCSessionState(oAuthMessage, sessionState, oauth2Params, authenticatedUser.getAuthenticatedSubjectIdentifier(), redirectURL, oAuthMessage.getSessionDataCacheEntry());
    }
    return Response.status(HttpServletResponse.SC_FOUND).location(new URI(redirectURL)).build();
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OIDCSessionState(org.wso2.carbon.identity.oidc.session.OIDCSessionState) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) URI(java.net.URI) REDIRECT_URI(org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Params.REDIRECT_URI)

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