Search in sources :

Example 1 with CommonAuthRequestWrapper

use of org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handleAuthFlowThroughFramework.

/**
 * This method use to call authentication framework directly via API other than using HTTP redirects.
 * Sending wrapper request object to doGet method since other original request doesn't exist required parameters
 * Doesn't check SUCCESS_COMPLETED since taking decision with INCOMPLETE status
 *
 * @param type authenticator type
 * @throws URISyntaxException
 * @throws InvalidRequestParentException
 * @Param type OAuthMessage
 */
private Response handleAuthFlowThroughFramework(OAuthMessage oAuthMessage, String type) throws URISyntaxException, InvalidRequestParentException {
    if (LoggerUtils.isDiagnosticLogsEnabled()) {
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", oAuthMessage.getClientId());
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Forward authorization request to framework for user authentication.", "hand-over-to-framework", null);
    }
    try {
        String sessionDataKey = (String) oAuthMessage.getRequest().getAttribute(FrameworkConstants.SESSION_DATA_KEY);
        CommonAuthenticationHandler commonAuthenticationHandler = new CommonAuthenticationHandler();
        CommonAuthRequestWrapper requestWrapper = new CommonAuthRequestWrapper(oAuthMessage.getRequest());
        requestWrapper.setParameter(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
        requestWrapper.setParameter(FrameworkConstants.RequestParams.TYPE, type);
        CommonAuthResponseWrapper responseWrapper = new CommonAuthResponseWrapper(oAuthMessage.getResponse());
        commonAuthenticationHandler.doGet(requestWrapper, responseWrapper);
        Object attribute = oAuthMessage.getRequest().getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS);
        if (attribute != null) {
            if (attribute == AuthenticatorFlowStatus.INCOMPLETE) {
                if (responseWrapper.isRedirect()) {
                    return Response.status(HttpServletResponse.SC_FOUND).location(buildURI(responseWrapper.getRedirectURL())).build();
                } else {
                    return Response.status(HttpServletResponse.SC_OK).entity(responseWrapper.getContent()).build();
                }
            } else {
                return authorize(requestWrapper, responseWrapper);
            }
        } else {
            requestWrapper.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.UNKNOWN);
            return authorize(requestWrapper, responseWrapper);
        }
    } catch (ServletException | IOException | URLBuilderException e) {
        log.error("Error occurred while sending request to authentication framework.");
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", oAuthMessage.getClientId());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Server error occurred.", "hand-over-to-framework", null);
        }
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)

Example 2 with CommonAuthRequestWrapper

use of org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper in project identity-inbound-auth-oauth by wso2-extensions.

the class OIDCLogoutServlet method sendRequestToFramework.

private void sendRequestToFramework(HttpServletRequest request, HttpServletResponse response, String sessionDataKey, String type) throws ServletException, IOException {
    CommonAuthenticationHandler commonAuthenticationHandler = new CommonAuthenticationHandler();
    CommonAuthRequestWrapper requestWrapper = new CommonAuthRequestWrapper(request);
    requestWrapper.setParameter(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
    requestWrapper.setParameter(FrameworkConstants.RequestParams.TYPE, type);
    CommonAuthResponseWrapper responseWrapper = new CommonAuthResponseWrapper(response);
    commonAuthenticationHandler.doGet(requestWrapper, responseWrapper);
    Object object = request.getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS);
    if (object != null) {
        AuthenticatorFlowStatus status = (AuthenticatorFlowStatus) object;
        if (status == AuthenticatorFlowStatus.INCOMPLETE) {
            if (responseWrapper.isRedirect()) {
                response.sendRedirect(responseWrapper.getRedirectURL());
            } else if (responseWrapper.getContent().length > 0) {
                responseWrapper.write();
            }
        } else {
            handleLogoutResponseFromFramework(requestWrapper, response);
        }
    } else {
        handleLogoutResponseFromFramework(requestWrapper, response);
    }
}
Also used : CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)

Example 3 with CommonAuthRequestWrapper

use of org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testHandleOAuthAuthorizationRequest.

/**
 * Tests the scenario of authorization request from the client
 */
@Test(dataProvider = "provideAuthzRequestData", groups = "testWithConnection")
public void testHandleOAuthAuthorizationRequest(String clientId, String redirectUri, String pkceChallengeCode, String pkceChallengeMethod, String prompt, boolean clientValid, boolean pkceEnabled, boolean supportPlainPkce, String expectedLocation) throws Exception {
    Map<String, String[]> requestParams = new HashMap();
    Map<String, Object> requestAttributes = new HashMap();
    requestParams.put(CLIENT_ID, new String[] { clientId });
    // No consent data is saved in the cache yet and client doesn't send cache key
    requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { null });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE, new String[] { pkceChallengeCode });
    requestParams.put(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE_METHOD, new String[] { pkceChallengeMethod });
    requestParams.put(OAuth.OAUTH_RESPONSE_TYPE, new String[] { ResponseType.TOKEN.toString() });
    if (redirectUri != null) {
        requestParams.put("acr_values", new String[] { redirectUri });
        requestParams.put("claims", new String[] { "essentialClaims" });
        requestParams.put(MultitenantConstants.TENANT_DOMAIN, new String[] { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME });
    }
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    // No authentication data is saved in the cache yet and client doesn't send cache key
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, null);
    if (prompt != null) {
        requestParams.put(OAuthConstants.OAuth20Params.PROMPT, new String[] { prompt });
    }
    boolean checkErrorCode = ERROR_PAGE_URL.equals(expectedLocation);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    mockOAuthServerConfiguration();
    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> responseTypeValidators = new Hashtable<>();
    responseTypeValidators.put(ResponseType.CODE.toString(), CodeValidator.class);
    responseTypeValidators.put(ResponseType.TOKEN.toString(), TokenValidator.class);
    when(oAuthServerConfiguration.getSupportedResponseTypeValidators()).thenReturn(responseTypeValidators);
    spy(FrameworkUtils.class);
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    IdentityEventService eventServiceMock = mock(IdentityEventService.class);
    mockStatic(CentralLogMgtServiceComponentHolder.class);
    when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
    when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
    PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    mockEndpointUtil(false);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    when(oAuth2Service.isPKCESupportEnabled()).thenReturn(pkceEnabled);
    if (ERROR_PAGE_URL.equals(expectedLocation) && OAuthConstants.Prompt.NONE.equals(prompt)) {
        doThrow(new IdentityOAuth2Exception("error")).when(EndpointUtil.class, "getLoginPageURL", anyString(), anyString(), anyBoolean(), anyBoolean(), anySet(), anyMap(), any());
        checkErrorCode = false;
    }
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
    validationResponseDTO.setValidClient(clientValid);
    validationResponseDTO.setCallbackURL(APP_REDIRECT_URL);
    if (!clientValid) {
        validationResponseDTO.setErrorCode(OAuth2ErrorCodes.INVALID_REQUEST);
        validationResponseDTO.setErrorMsg("client is invalid");
    }
    validationResponseDTO.setPkceMandatory(supportPlainPkce);
    validationResponseDTO.setPkceSupportPlain(supportPlainPkce);
    when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(validationResponseDTO);
    if (StringUtils.equals(expectedLocation, LOGIN_PAGE_URL) || StringUtils.equals(expectedLocation, ERROR_PAGE_URL)) {
        CommonAuthenticationHandler handler = mock(CommonAuthenticationHandler.class);
        doAnswer(invocation -> {
            CommonAuthRequestWrapper request = (CommonAuthRequestWrapper) invocation.getArguments()[0];
            request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
            CommonAuthResponseWrapper wrapper = (CommonAuthResponseWrapper) invocation.getArguments()[1];
            wrapper.sendRedirect(expectedLocation);
            return null;
        }).when(handler).doGet(any(), any());
        whenNew(CommonAuthenticationHandler.class).withNoArguments().thenReturn(handler);
    }
    mockServiceURLBuilder();
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response);
    assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND, "Unexpected HTTP response status");
    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(expectedLocation), "Unexpected redirect url in the response");
    if (checkErrorCode) {
        assertTrue(location.contains(OAuth2ErrorCodes.INVALID_REQUEST), "Expected error code not found in URL");
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) OAuth2ClientValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO) Matchers.anyString(org.mockito.Matchers.anyString) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) 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) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 4 with CommonAuthRequestWrapper

use of org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper in project identity-inbound-auth-oauth by wso2-extensions.

the class UserAuthenticationEndpoint method deviceAuthorize.

@POST
@Path("/")
@Consumes("application/x-www-form-urlencoded")
@Produces("text/html")
public Response deviceAuthorize(@Context HttpServletRequest request, @Context HttpServletResponse response) throws InvalidRequestParentException, OAuthSystemException {
    try {
        String userCode = request.getParameter(Constants.USER_CODE);
        // True when input(user_code) is not REQUIRED.
        if (StringUtils.isBlank(userCode)) {
            if (log.isDebugEnabled()) {
                log.debug("user_code is missing in the request.");
            }
            response.sendRedirect(ServiceURLBuilder.create().addPath(Constants.DEVICE_ENDPOINT_PATH).addParameter("error", OAuth2ErrorCodes.INVALID_REQUEST).build().getAbsolutePublicURL());
            return null;
        }
        String clientId = deviceAuthService.getClientId(userCode);
        DeviceFlowDO deviceFlowDODetails = DeviceFlowPersistenceFactory.getInstance().getDeviceFlowDAO().getDetailsForUserCode(userCode);
        if (StringUtils.isNotBlank(clientId) && deviceFlowDODetails != null && !isExpiredUserCode(deviceFlowDODetails)) {
            setCallbackURI(clientId);
            deviceAuthService.setAuthenticationStatus(userCode);
            CommonAuthRequestWrapper commonAuthRequestWrapper = new CommonAuthRequestWrapper(request);
            commonAuthRequestWrapper.setParameter(Constants.CLIENT_ID, clientId);
            commonAuthRequestWrapper.setParameter(Constants.RESPONSE_TYPE, Constants.RESPONSE_TYPE_DEVICE);
            commonAuthRequestWrapper.setParameter(Constants.REDIRECTION_URI, deviceFlowDO.getCallbackUri());
            if (getScope(userCode) != null) {
                String scope = String.join(Constants.SEPARATED_WITH_SPACE, getScope(userCode));
                commonAuthRequestWrapper.setParameter(Constants.SCOPE, scope);
            }
            commonAuthRequestWrapper.setParameter(Constants.NONCE, userCode);
            return oAuth2AuthzEndpoint.authorize(commonAuthRequestWrapper, response);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Incorrect user_code.");
            }
            response.sendRedirect(ServiceURLBuilder.create().addPath(Constants.DEVICE_ENDPOINT_PATH).addParameter("error", OAuth2ErrorCodes.INVALID_REQUEST).build().getAbsolutePublicURL());
            return null;
        }
    } catch (IdentityOAuth2Exception e) {
        return handleIdentityOAuth2Exception(e);
    } catch (IOException e) {
        return handleIOException(e);
    } catch (URLBuilderException e) {
        return handleURLBuilderException(e);
    } catch (URISyntaxException e) {
        return handleURISyntaxException(e);
    }
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) DeviceFlowDO(org.wso2.carbon.identity.oauth2.device.model.DeviceFlowDO) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

CommonAuthRequestWrapper (org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper)4 CommonAuthenticationHandler (org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler)3 CommonAuthResponseWrapper (org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 URLBuilderException (org.wso2.carbon.identity.core.URLBuilderException)2 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)2 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)2 URISyntaxException (java.net.URISyntaxException)1 Hashtable (java.util.Hashtable)1 Map (java.util.Map)1 ServletException (javax.servlet.ServletException)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 Consumes (javax.ws.rs.Consumes)1 POST (javax.ws.rs.POST)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)1 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)1