Search in sources :

Example 1 with OAuthMessage

use of org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testHandleOAuthAuthorizationRequest1.

@Test(dataProvider = "provideHandleOAuthAuthorizationRequest1Data", groups = "testWithConnection")
public void testHandleOAuthAuthorizationRequest1(boolean showDisplayName, Object spObj, String savedDisplayName) throws Exception {
    ServiceProvider sp = (ServiceProvider) spObj;
    sp.setApplicationName(APP_NAME);
    mockApplicationManagementService(sp);
    mockOAuthServerConfiguration();
    mockEndpointUtil(false);
    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);
    Map<String, String[]> requestParams = new HashMap();
    Map<String, Object> requestAttributes = new HashMap();
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuth.OAUTH_RESPONSE_TYPE, new String[] { ResponseType.TOKEN.toString() });
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
    validationResponseDTO.setValidClient(true);
    validationResponseDTO.setCallbackURL(APP_REDIRECT_URL);
    when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(validationResponseDTO);
    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);
    when(oAuthServerConfiguration.isShowDisplayNameInConsentPage()).thenReturn(showDisplayName);
    Method handleOAuthAuthorizationRequest = authzEndpointObject.getClass().getDeclaredMethod("handleOAuthAuthorizationRequest", OAuthMessage.class);
    handleOAuthAuthorizationRequest.setAccessible(true);
    SessionDataCache sessionDataCache = mock(SessionDataCache.class);
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    final SessionDataCacheEntry[] cacheEntry = new SessionDataCacheEntry[1];
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) {
            cacheEntry[0] = (SessionDataCacheEntry) invocation.getArguments()[1];
            return null;
        }
    }).when(sessionDataCache).addToCache(any(SessionDataCacheKey.class), any(SessionDataCacheEntry.class));
    when(oAuthMessage.getRequest()).thenReturn(httpServletRequest);
    when(oAuthMessage.getClientId()).thenReturn(CLIENT_ID_VALUE);
    handleOAuthAuthorizationRequest.invoke(authzEndpointObject, oAuthMessage);
    assertNotNull(cacheEntry[0], "Parameters not saved in cache");
    assertEquals(cacheEntry[0].getoAuth2Parameters().getDisplayName(), savedDisplayName);
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) SessionDataCache(org.wso2.carbon.identity.oauth.cache.SessionDataCache) OAuth2ClientValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO) Matchers.anyString(org.mockito.Matchers.anyString) HttpMethod(javax.ws.rs.HttpMethod) Method(java.lang.reflect.Method) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) 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 2 with OAuthMessage

use of org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage in project identity-inbound-auth-oauth by wso2-extensions.

the class EndpointUtil method getUserConsentURL.

/**
 * Returns the consent page URL.
 *
 * @param params            OAuth2 Parameters.
 * @param loggedInUser      The logged in user
 * @param isOIDC            Whether the flow is an OIDC or not.
 * @param oAuthMessage      oAuth Message.
 * @return                  The consent url.
 */
public static String getUserConsentURL(OAuth2Parameters params, String loggedInUser, String sessionDataKey, boolean isOIDC, OAuthMessage oAuthMessage) throws OAuthSystemException {
    String queryString = "";
    if (log.isDebugEnabled()) {
        log.debug("Received Session Data Key is :  " + sessionDataKey);
        if (params == null) {
            log.debug("Received OAuth2 params are Null for UserConsentURL");
        }
    }
    SessionDataCache sessionDataCache = SessionDataCache.getInstance();
    SessionDataCacheEntry entry;
    if (oAuthMessage != null) {
        entry = oAuthMessage.getResultFromLogin();
    } else {
        entry = sessionDataCache.getValueFromCache(new SessionDataCacheKey(sessionDataKey));
    }
    AuthenticatedUser user = null;
    String consentPage = null;
    String sessionDataKeyConsent = UUID.randomUUID().toString();
    try {
        if (entry != null && entry.getQueryString() != null) {
            if (entry.getQueryString().contains(REQUEST_URI) && params != null) {
                // When request_uri requests come without redirect_uri, we need to append it to the SPQueryParams
                // to be used in storing consent data
                entry.setQueryString(entry.getQueryString() + "&" + PROP_REDIRECT_URI + "=" + params.getRedirectURI());
            }
            queryString = URLEncoder.encode(entry.getQueryString(), UTF_8);
        }
        if (isOIDC) {
            consentPage = OAuth2Util.OAuthURL.getOIDCConsentPageUrl();
        } else {
            consentPage = OAuth2Util.OAuthURL.getOAuth2ConsentPageUrl();
        }
        if (params != null) {
            consentPage += "?" + OAuthConstants.OIDC_LOGGED_IN_USER + "=" + URLEncoder.encode(loggedInUser, UTF_8) + "&application=";
            if (StringUtils.isNotEmpty(params.getDisplayName())) {
                consentPage += URLEncoder.encode(params.getDisplayName(), UTF_8);
            } else {
                consentPage += URLEncoder.encode(params.getApplicationName(), UTF_8);
            }
            consentPage += "&tenantDomain=" + getSPTenantDomainFromClientId(params.getClientId());
            if (entry != null) {
                user = entry.getLoggedInUser();
            }
            setConsentRequiredScopesToOAuthParams(user, params);
            Set<String> consentRequiredScopesSet = params.getConsentRequiredScopes();
            String consentRequiredScopes = StringUtils.EMPTY;
            if (CollectionUtils.isNotEmpty(consentRequiredScopesSet)) {
                consentRequiredScopes = String.join(" ", consentRequiredScopesSet).trim();
            }
            consentPage = consentPage + "&" + OAuthConstants.OAuth20Params.SCOPE + "=" + URLEncoder.encode(consentRequiredScopes, UTF_8) + "&" + OAuthConstants.SESSION_DATA_KEY_CONSENT + "=" + URLEncoder.encode(sessionDataKeyConsent, UTF_8) + "&" + "&spQueryParams=" + queryString;
            if (entry != null) {
                consentPage = FrameworkUtils.getRedirectURLWithFilteredParams(consentPage, entry.getEndpointParams());
                entry.setValidityPeriod(TimeUnit.MINUTES.toNanos(IdentityUtil.getTempDataCleanUpTimeout()));
                sessionDataCache.addToCache(new SessionDataCacheKey(sessionDataKeyConsent), entry);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Cache Entry is Null from SessionDataCache.");
                }
            }
        } else {
            throw new OAuthSystemException("Error while retrieving the application name");
        }
    } catch (UnsupportedEncodingException e) {
        throw new OAuthSystemException("Error while encoding the url", e);
    }
    return consentPage;
}
Also used : SessionDataCache(org.wso2.carbon.identity.oauth.cache.SessionDataCache) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 3 with OAuthMessage

use of org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage 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 4 with OAuthMessage

use of org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handleEmptyConsent.

private Response handleEmptyConsent(OAuthMessage oAuthMessage) throws URISyntaxException {
    String appName = getOauth2Params(oAuthMessage).getApplicationName();
    if (log.isDebugEnabled()) {
        log.debug("Invalid authorization request. \'sessionDataKey\' parameter found but \'consent\' " + "parameter could not be found in request");
    }
    OAuth2Parameters oAuth2Parameters = getOAuth2ParamsFromOAuthMessage(oAuthMessage);
    return Response.status(HttpServletResponse.SC_FOUND).location(new URI(getErrorPageURL(oAuthMessage.getRequest(), OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_AUTHORIZATION_REQUEST, "Invalid authorization request", appName, oAuth2Parameters))).build();
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) URI(java.net.URI) REDIRECT_URI(org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Params.REDIRECT_URI)

Example 5 with OAuthMessage

use of org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method addToBCLogoutSessionToOAuthMessage.

/**
 * Store Authorization Code and SessionID for back-channel logout in the cache.
 *
 * @param oAuthMessage
 * @param sessionId
 */
private void addToBCLogoutSessionToOAuthMessage(OAuthMessage oAuthMessage, String sessionId) {
    AuthorizationGrantCacheEntry entry = oAuthMessage.getAuthorizationGrantCacheEntry();
    if (entry == null) {
        log.debug("Authorization code is not found in the redirect URL");
        return;
    }
    entry.setOidcSessionId(sessionId);
}
Also used : AuthorizationGrantCacheEntry(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry)

Aggregations

HashMap (java.util.HashMap)15 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)15 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)14 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)14 JSONObject (org.json.JSONObject)11 URI (java.net.URI)7 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)7 REDIRECT_URI (org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Params.REDIRECT_URI)7 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)6 SessionDataCacheEntry (org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry)4 IOException (java.io.IOException)3 Method (java.lang.reflect.Method)3 Map (java.util.Map)3 HttpMethod (javax.ws.rs.HttpMethod)3 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)3 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)3 Matchers.anyString (org.mockito.Matchers.anyString)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 AfterTest (org.testng.annotations.AfterTest)3 BeforeTest (org.testng.annotations.BeforeTest)3