Search in sources :

Example 1 with JDBCPermissionBasedInternalScopeValidator

use of org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator in project identity-inbound-auth-oauth by wso2-extensions.

the class AuthorizationHandlerManager method validateAuthzRequest.

private OAuth2AuthorizeRespDTO validateAuthzRequest(OAuth2AuthorizeReqDTO authzReqDTO, OAuthAuthzReqMessageContext authzReqMsgCtx, ResponseTypeHandler authzHandler) throws IdentityOAuth2Exception {
    OAuth2AuthorizeRespDTO authorizeRespDTO = new OAuth2AuthorizeRespDTO();
    if (isInvalidResponseType(authzReqDTO, authorizeRespDTO)) {
        return authorizeRespDTO;
    }
    if (isInvalidClient(authzReqDTO, authorizeRespDTO, authzReqMsgCtx, authzHandler)) {
        return authorizeRespDTO;
    }
    if (isInvalidAccessDelegation(authzReqDTO, authorizeRespDTO, authzReqMsgCtx, authzHandler)) {
        return authorizeRespDTO;
    }
    List<String> allowedScopes = OAuthServerConfiguration.getInstance().getAllowedScopes();
    List<String> requestedAllowedScopes = new ArrayList<>();
    String[] requestedScopes = authzReqMsgCtx.getAuthorizationReqDTO().getScopes();
    List<String> scopesToBeValidated = new ArrayList<>();
    if (requestedScopes != null) {
        for (String scope : requestedScopes) {
            if (OAuth2Util.isAllowedScope(allowedScopes, scope)) {
                requestedAllowedScopes.add(scope);
            } else {
                scopesToBeValidated.add(scope);
            }
        }
        authzReqMsgCtx.getAuthorizationReqDTO().setScopes(scopesToBeValidated.toArray(new String[0]));
    }
    // Execute Internal SCOPE Validation.
    String[] authorizedInternalScopes = new String[0];
    boolean isManagementApp = isManagementApp(authzReqDTO);
    if (isManagementApp) {
        if (log.isDebugEnabled()) {
            log.debug("Handling the internal scope validation.");
        }
        JDBCPermissionBasedInternalScopeValidator scopeValidator = new JDBCPermissionBasedInternalScopeValidator();
        authorizedInternalScopes = scopeValidator.validateScope(authzReqMsgCtx);
        // Execute internal console scopes validation.
        if (IdentityUtil.isSystemRolesEnabled()) {
            RoleBasedInternalScopeValidator roleBasedInternalScopeValidator = new RoleBasedInternalScopeValidator();
            String[] roleBasedInternalConsoleScopes = roleBasedInternalScopeValidator.validateScope(authzReqMsgCtx);
            authorizedInternalScopes = (String[]) ArrayUtils.addAll(authorizedInternalScopes, roleBasedInternalConsoleScopes);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Skipping the internal scope validation as the application is not" + " configured as Management App");
        }
    }
    // Clear the internal scopes. Internal scopes should only handle in JDBCPermissionBasedInternalScopeValidator.
    // Those scopes should not send to the other scopes validators.
    // Thus remove the scopes from the authzReqMsgCtx. Will be added to the response after executing
    // the other scope validators.
    removeInternalScopes(authzReqMsgCtx);
    // Adding the authorized internal scopes to tokReqMsgCtx for any special validators to use.
    authzReqMsgCtx.setAuthorizedInternalScopes(authorizedInternalScopes);
    boolean isDropUnregisteredScopes = OAuthServerConfiguration.getInstance().isDropUnregisteredScopes();
    if (isDropUnregisteredScopes) {
        if (log.isDebugEnabled()) {
            log.debug("DropUnregisteredScopes config is enabled. Attempting to drop unregistered scopes.");
        }
        String[] filteredScopes = OAuth2Util.dropUnregisteredScopes(authzReqMsgCtx.getAuthorizationReqDTO().getScopes(), authzReqMsgCtx.getAuthorizationReqDTO().getTenantDomain());
        authzReqMsgCtx.getAuthorizationReqDTO().setScopes(filteredScopes);
    }
    boolean valid = validateScope(authzReqDTO, authorizeRespDTO, authzReqMsgCtx, authzHandler);
    if (valid) {
        // Add authorized internal scopes to the request for sending in the response.
        addAuthorizedInternalScopes(authzReqMsgCtx, authzReqMsgCtx.getAuthorizedInternalScopes());
        addAllowedScopes(authzReqMsgCtx, requestedAllowedScopes.toArray(new String[0]));
    }
    return authorizeRespDTO;
}
Also used : RoleBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.RoleBasedInternalScopeValidator) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) ArrayList(java.util.ArrayList)

Example 2 with JDBCPermissionBasedInternalScopeValidator

use of org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator in project identity-inbound-auth-oauth by wso2-extensions.

the class EndpointUtil method setConsentRequiredScopesToOAuthParams.

private static void setConsentRequiredScopesToOAuthParams(AuthenticatedUser user, OAuth2Parameters params) throws OAuthSystemException {
    try {
        String consentRequiredScopes = StringUtils.EMPTY;
        List<String> allowedOAuthScopes = getAllowedOAuthScopes(params);
        if (user != null && !isPromptContainsConsent(params)) {
            String userId = getUserIdOfAuthenticatedUser(user);
            String appId = getAppIdFromClientId(params.getClientId());
            OAuth2ScopeConsentResponse existingUserConsent = oAuth2ScopeService.getUserConsentForApp(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()));
            if (existingUserConsent != null) {
                if (CollectionUtils.isNotEmpty(existingUserConsent.getApprovedScopes())) {
                    allowedOAuthScopes.removeAll(existingUserConsent.getApprovedScopes());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(allowedOAuthScopes)) {
            // Filter out internal scopes to be validated.
            String[] requestedScopes = Oauth2ScopeUtils.getRequestedScopes(allowedOAuthScopes.toArray(new String[0]));
            if (ArrayUtils.isNotEmpty(requestedScopes)) {
                // Remove the filtered internal scopes from the allowedOAuthScopes list.
                allowedOAuthScopes.removeAll(Arrays.asList(requestedScopes));
                JDBCPermissionBasedInternalScopeValidator scopeValidator = new JDBCPermissionBasedInternalScopeValidator();
                String[] validatedScope = scopeValidator.validateScope(requestedScopes, user, params.getClientId());
                // Filter out requested scopes from the validated scope array.
                for (String scope : requestedScopes) {
                    if (ArrayUtils.contains(validatedScope, scope)) {
                        allowedOAuthScopes.add(scope);
                    }
                }
            }
            params.setConsentRequiredScopes(new HashSet<>(allowedOAuthScopes));
            consentRequiredScopes = String.join(" ", allowedOAuthScopes).trim();
        }
        if (log.isDebugEnabled()) {
            log.debug("Consent required scopes : " + consentRequiredScopes + " for request from client : " + params.getClientId());
        }
    } catch (IdentityOAuth2ScopeException e) {
        throw new OAuthSystemException("Error occurred while retrieving user consents OAuth scopes.");
    }
}
Also used : OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) IdentityOAuth2ScopeException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException)

Example 3 with JDBCPermissionBasedInternalScopeValidator

use of org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator in project identity-inbound-auth-oauth by wso2-extensions.

the class EndpointUtilTest method testGetUserConsentURL.

@Test(dataProvider = "provideDataForUserConsentURL")
public void testGetUserConsentURL(Object oAuth2ParamObject, boolean isOIDC, boolean cacheEntryExists, boolean throwError, String queryString, boolean isDebugEnabled) throws Exception {
    setMockedLog(isDebugEnabled);
    OAuth2Parameters parameters = (OAuth2Parameters) oAuth2ParamObject;
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(mockedOAuthServerConfiguration);
    EndpointUtil.setOauthServerConfiguration(mockedOAuthServerConfiguration);
    when(mockedOAuthServerConfiguration.isDropUnregisteredScopes()).thenReturn(false);
    EndpointUtil.setOAuth2ScopeService(oAuth2ScopeService);
    when(oAuth2ScopeService.getUserConsentForApp(anyString(), anyString(), anyInt())).thenReturn(oAuth2ScopeConsentResponse);
    mockStatic(OAuth2Util.class);
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOIDCConsentPageUrl()).thenReturn(OIDC_CONSENT_PAGE_URL);
    when(OAuth2Util.OAuthURL.getOAuth2ConsentPageUrl()).thenReturn(OAUTH2_CONSENT_PAGE_URL);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockStatic(FrameworkUtils.class);
    when(FrameworkUtils.resolveUserIdFromUsername(anyInt(), anyString(), anyString())).thenReturn("sample");
    when(FrameworkUtils.getRedirectURLWithFilteredParams(anyString(), anyMap())).then(i -> i.getArgumentAt(0, String.class));
    mockStatic(OAuth2Util.class);
    spy(EndpointUtil.class);
    doReturn("sampleId").when(EndpointUtil.class, "getAppIdFromClientId", anyString());
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(mockedSessionDataCache);
    if (cacheEntryExists) {
        when(mockedSessionDataCache.getValueFromCache(any(SessionDataCacheKey.class))).thenReturn(mockedSessionDataCacheEntry);
        when(mockedSessionDataCacheEntry.getQueryString()).thenReturn(queryString);
        when(mockedSessionDataCacheEntry.getLoggedInUser()).thenReturn(user);
        when(mockedSessionDataCacheEntry.getEndpointParams()).thenReturn(new HashMap<>());
    } else {
        when(mockedSessionDataCache.getValueFromCache(any(SessionDataCacheKey.class))).thenReturn(null);
    }
    EndpointUtil.setOAuthAdminService(mockedOAuthAdminService);
    when(mockedOAuthAdminService.getScopeNames()).thenReturn(new String[0]);
    JDBCPermissionBasedInternalScopeValidator scopeValidatorSpy = PowerMockito.spy(new JDBCPermissionBasedInternalScopeValidator());
    doNothing().when(scopeValidatorSpy, method(JDBCPermissionBasedInternalScopeValidator.class, "endTenantFlow")).withNoArguments();
    when(scopeValidatorSpy, method(JDBCPermissionBasedInternalScopeValidator.class, "getUserAllowedScopes", AuthenticatedUser.class, String[].class, String.class)).withArguments(any(AuthenticatedUser.class), any(), anyString()).thenReturn(getScopeList());
    PowerMockito.whenNew(JDBCPermissionBasedInternalScopeValidator.class).withNoArguments().thenReturn(scopeValidatorSpy);
    String consentUrl;
    try {
        consentUrl = EndpointUtil.getUserConsentURL(parameters, username, sessionDataKey, isOIDC);
        if (isOIDC) {
            Assert.assertTrue(consentUrl.contains(OIDC_CONSENT_PAGE_URL), "Incorrect consent page url for OIDC");
        } else {
            Assert.assertTrue(consentUrl.contains(OAUTH2_CONSENT_PAGE_URL), "Incorrect consent page url for OAuth");
        }
        Assert.assertTrue(consentUrl.contains(URLEncoder.encode(username, "UTF-8")), "loggedInUser parameter value is not found in url");
        Assert.assertTrue(consentUrl.contains(URLEncoder.encode("TestApplication", "ISO-8859-1")), "application parameter value is not found in url");
        List<NameValuePair> nameValuePairList = URLEncodedUtils.parse(consentUrl, StandardCharsets.UTF_8);
        Optional<NameValuePair> optionalScope = nameValuePairList.stream().filter(nameValuePair -> nameValuePair.getName().equals("scope")).findAny();
        Assert.assertTrue(optionalScope.isPresent());
        NameValuePair scopeNameValuePair = optionalScope.get();
        String[] scopeArray = scopeNameValuePair.getValue().split(" ");
        Assert.assertTrue(ArrayUtils.contains(scopeArray, "scope2"), "scope parameter value " + "is not found in url");
        Assert.assertTrue(ArrayUtils.contains(scopeArray, "internal_login"), "internal_login " + "scope parameter value is not found in url");
        Assert.assertFalse(ArrayUtils.contains(scopeArray, "SYSTEM"), "SYSTEM scope" + "parameter should not contain in the url.");
        if (queryString != null && cacheEntryExists) {
            Assert.assertTrue(consentUrl.contains(queryString), "spQueryParams value is not found in url");
        }
    } catch (OAuthSystemException e) {
        Assert.assertTrue(e.getMessage().contains("Error while retrieving the application name"));
    }
}
Also used : OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Scope(org.wso2.carbon.identity.oauth2.bean.Scope) Arrays(java.util.Arrays) DefaultOIDCProcessor(org.wso2.carbon.identity.discovery.DefaultOIDCProcessor) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Test(org.testng.annotations.Test) ServiceURL(org.wso2.carbon.identity.core.ServiceURL) PowerMockito.doNothing(org.powermock.api.mockito.PowerMockito.doNothing) AuthenticationRequestCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry) Map(java.util.Map) URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) Matchers.anyInt(org.mockito.Matchers.anyInt) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) PowerMockito.whenNew(org.powermock.api.mockito.PowerMockito.whenNew) OAuthAdminServiceImpl(org.wso2.carbon.identity.oauth.OAuthAdminServiceImpl) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) OAuthClientException(org.wso2.carbon.identity.oauth.common.exception.OAuthClientException) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) Set(java.util.Set) PowerMockito.doReturn(org.powermock.api.mockito.PowerMockito.doReturn) HashedMap(org.apache.commons.collections.map.HashedMap) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.any(org.mockito.Matchers.any) List(java.util.List) PowerMockito.mock(org.powermock.api.mockito.PowerMockito.mock) OAuth2Service(org.wso2.carbon.identity.oauth2.OAuth2Service) Matchers.anyMap(org.mockito.Matchers.anyMap) URLEncodedUtils(org.apache.http.client.utils.URLEncodedUtils) Modifier(java.lang.reflect.Modifier) PowerMockito.doAnswer(org.powermock.api.mockito.PowerMockito.doAnswer) Optional(java.util.Optional) OIDCProcessor(org.wso2.carbon.identity.discovery.OIDCProcessor) NameValuePair(org.apache.http.NameValuePair) FrameworkUtils(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils) MemberMatcher.method(org.powermock.api.support.membermodification.MemberMatcher.method) DefaultOIDCProviderRequestBuilder(org.wso2.carbon.identity.discovery.builders.DefaultOIDCProviderRequestBuilder) OAuth2ScopeService(org.wso2.carbon.identity.oauth2.OAuth2ScopeService) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) DataProvider(org.testng.annotations.DataProvider) PowerMockito.mockStatic(org.powermock.api.mockito.PowerMockito.mockStatic) Mock(org.mockito.Mock) Assert.assertEquals(org.testng.Assert.assertEquals) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) HashMap(java.util.HashMap) Constructor(java.lang.reflect.Constructor) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) BeforeTest(org.testng.annotations.BeforeTest) HttpServletRequest(javax.servlet.http.HttpServletRequest) Assert(org.testng.Assert) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) Base64Utils(org.apache.axiom.util.base64.Base64Utils) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) LoggerUtils(org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils) MultitenantConstants(org.wso2.carbon.base.MultitenantConstants) SessionDataCache(org.wso2.carbon.identity.oauth.cache.SessionDataCache) WebFingerProcessor(org.wso2.carbon.identity.webfinger.WebFingerProcessor) PowerMockito(org.powermock.api.mockito.PowerMockito) SSOConsentService(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.SSOConsentService) IdentityTenantUtil(org.wso2.carbon.identity.core.util.IdentityTenantUtil) WithCarbonHome(org.wso2.carbon.identity.common.testng.WithCarbonHome) PowerMockito.when(org.powermock.api.mockito.PowerMockito.when) HttpServletResponse(javax.servlet.http.HttpServletResponse) Field(java.lang.reflect.Field) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ServerConfiguration(org.wso2.carbon.base.ServerConfiguration) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) OAuth2TokenValidationService(org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest) URLEncoder(java.net.URLEncoder) FileBasedConfigurationBuilder(org.wso2.carbon.identity.application.authentication.framework.config.builder.FileBasedConfigurationBuilder) DefaultWebFingerProcessor(org.wso2.carbon.identity.webfinger.DefaultWebFingerProcessor) PowerMockito.spy(org.powermock.api.mockito.PowerMockito.spy) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OIDCProviderRequestBuilder(org.wso2.carbon.identity.discovery.builders.OIDCProviderRequestBuilder) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) RequestObjectService(org.wso2.carbon.identity.openidconnect.RequestObjectService) IdentityUtil(org.wso2.carbon.identity.core.util.IdentityUtil) Assert.assertTrue(org.testng.Assert.assertTrue) Log(org.apache.commons.logging.Log) ArrayUtils(org.apache.commons.lang.ArrayUtils) NameValuePair(org.apache.http.NameValuePair) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 4 with JDBCPermissionBasedInternalScopeValidator

use of org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator in project identity-inbound-auth-oauth by wso2-extensions.

the class AccessTokenIssuer method issue.

/**
 * Issue access token using the respective grant handler and client authentication handler.
 *
 * @param tokenReqDTO
 * @return access token response
 * @throws IdentityException
 * @throws InvalidOAuthClientException
 */
public OAuth2AccessTokenRespDTO issue(OAuth2AccessTokenReqDTO tokenReqDTO) throws IdentityException {
    String grantType = tokenReqDTO.getGrantType();
    OAuth2AccessTokenRespDTO tokenRespDTO = null;
    AuthorizationGrantHandler authzGrantHandler = authzGrantHandlers.get(grantType);
    OAuthTokenReqMessageContext tokReqMsgCtx = new OAuthTokenReqMessageContext(tokenReqDTO);
    boolean isRefreshRequest = GrantType.REFRESH_TOKEN.toString().equals(grantType);
    triggerPreListeners(tokenReqDTO, tokReqMsgCtx, isRefreshRequest);
    OAuthClientAuthnContext oAuthClientAuthnContext = tokenReqDTO.getoAuthClientAuthnContext();
    if (oAuthClientAuthnContext == null) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            if (StringUtils.isNotBlank(tokenReqDTO.getClientSecret())) {
                params.put("clientSecret", tokenReqDTO.getClientSecret().replaceAll(".", "*"));
            }
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "OAuth client authentication failed.", "issue-access-token", null);
        }
        oAuthClientAuthnContext = new OAuthClientAuthnContext();
        oAuthClientAuthnContext.setAuthenticated(false);
        oAuthClientAuthnContext.setErrorMessage("Client Authentication Failed");
        oAuthClientAuthnContext.setErrorCode(OAuthError.TokenResponse.INVALID_REQUEST);
    }
    // whether the grant type is confidential or not.
    if (oAuthClientAuthnContext.isMultipleAuthenticatorsEngaged()) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            params.put("clientAuthenticators", oAuthClientAuthnContext.getExecutedAuthenticators());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "The client MUST NOT use more than one authentication method per request.", "issue-access-token", null);
        }
        tokenRespDTO = handleError(OAuth2ErrorCodes.INVALID_REQUEST, "The client MUST NOT use more than one " + "authentication method in each", tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    boolean isAuthenticated = oAuthClientAuthnContext.isAuthenticated();
    if (authzGrantHandler == null) {
        String errorMsg = "Unsupported grant type : " + grantType + ", is used.";
        if (log.isDebugEnabled()) {
            log.debug(errorMsg);
        }
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            params.put("grantType", grantType);
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Unsupported grant type.", "issue-access-token", null);
        }
        tokenRespDTO = handleError(OAuthError.TokenResponse.UNSUPPORTED_GRANT_TYPE, errorMsg, tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    // If the client is not confidential then there is no need to authenticate the client.
    if (!authzGrantHandler.isConfidentialClient() && StringUtils.isNotEmpty(oAuthClientAuthnContext.getClientId())) {
        isAuthenticated = true;
    }
    if (!isAuthenticated && !oAuthClientAuthnContext.isPreviousAuthenticatorEngaged() && authzGrantHandler.isConfidentialClient()) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Unsupported client authentication method.", "issue-access-token", null);
        }
        tokenRespDTO = handleError(OAuth2ErrorCodes.INVALID_CLIENT, "Unsupported Client Authentication Method!", tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    if (!isAuthenticated) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Client authentication failed. " + oAuthClientAuthnContext.getErrorMessage(), "issue-access-token", null);
        }
        tokenRespDTO = handleError(oAuthClientAuthnContext.getErrorCode(), oAuthClientAuthnContext.getErrorMessage(), tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    // loading the stored application data
    OAuthAppDO oAuthAppDO = getOAuthApplication(tokenReqDTO.getClientId());
    // set the tenantDomain of the SP in the tokenReqDTO
    // Indirectly we can say that the tenantDomain of the SP is the tenantDomain of the user who created SP.
    // This is done to avoid having to send the tenantDomain as a query param to the token endpoint
    String tenantDomainOfApp = OAuth2Util.getTenantDomainOfOauthApp(oAuthAppDO);
    validateRequestTenantDomain(tenantDomainOfApp);
    tokenReqDTO.setTenantDomain(tenantDomainOfApp);
    tokReqMsgCtx.addProperty(OAUTH_APP_DO, oAuthAppDO);
    boolean isOfTypeApplicationUser = authzGrantHandler.isOfTypeApplicationUser();
    if (!isOfTypeApplicationUser) {
        tokReqMsgCtx.setAuthorizedUser(oAuthAppDO.getAppOwner());
        tokReqMsgCtx.addProperty(OAuthConstants.UserType.USER_TYPE, OAuthConstants.UserType.APPLICATION);
    } else {
        tokReqMsgCtx.addProperty(OAuthConstants.UserType.USER_TYPE, OAuthConstants.UserType.APPLICATION_USER);
    }
    boolean isAuthorizedClient = false;
    String error = "The authenticated client is not authorized to use this authorization grant type";
    try {
        isAuthorizedClient = authzGrantHandler.isAuthorizedClient(tokReqMsgCtx);
    } catch (IdentityOAuth2Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while validating client for authorization", e);
        }
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "issue-access-token", null);
        error = e.getMessage();
    }
    if (!isAuthorizedClient) {
        if (log.isDebugEnabled()) {
            log.debug("Client Id: " + tokenReqDTO.getClientId() + " is not authorized to use grant type: " + grantType);
        }
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            params.put("grantType", grantType);
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Client is not authorized to use the requested grant type.", "issue-access-token", null);
        }
        tokenRespDTO = handleError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT, error, tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    boolean isValidGrant = false;
    error = "Provided Authorization Grant is invalid";
    String errorCode = OAuthError.TokenResponse.INVALID_GRANT;
    try {
        isValidGrant = authzGrantHandler.validateGrant(tokReqMsgCtx);
    } catch (IdentityOAuth2Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while validating grant", e);
        }
        if (e.getErrorCode() != null) {
            errorCode = e.getErrorCode();
        }
        error = e.getMessage();
        if (e.getErrorCode() != null) {
            errorCode = e.getErrorCode();
        }
    }
    if (tokReqMsgCtx.getAuthorizedUser() != null && tokReqMsgCtx.getAuthorizedUser().isFederatedUser()) {
        tokReqMsgCtx.getAuthorizedUser().setTenantDomain(tenantDomainOfApp);
    }
    if (!isValidGrant) {
        if (log.isDebugEnabled()) {
            log.debug("Invalid Grant provided by the client Id: " + tokenReqDTO.getClientId());
        }
        tokenRespDTO = handleError(errorCode, error, tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    boolean isAuthorized = authzGrantHandler.authorizeAccessDelegation(tokReqMsgCtx);
    if (!isAuthorized) {
        if (log.isDebugEnabled()) {
            log.debug("Invalid authorization for client Id : " + tokenReqDTO.getClientId());
        }
        tokenRespDTO = handleError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT, "Unauthorized Client!", tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    List<String> allowedScopes = OAuthServerConfiguration.getInstance().getAllowedScopes();
    List<String> requestedAllowedScopes = new ArrayList<>();
    String[] requestedScopes = tokReqMsgCtx.getScope();
    List<String> scopesToBeValidated = new ArrayList<>();
    if (requestedScopes != null) {
        for (String scope : requestedScopes) {
            if (OAuth2Util.isAllowedScope(allowedScopes, scope)) {
                requestedAllowedScopes.add(scope);
            } else {
                scopesToBeValidated.add(scope);
            }
        }
        tokReqMsgCtx.setScope(scopesToBeValidated.toArray(new String[0]));
    }
    String[] authorizedInternalScopes = new String[0];
    boolean isManagementApp = getServiceProvider(tokenReqDTO).isManagementApp();
    if (isManagementApp) {
        if (log.isDebugEnabled()) {
            log.debug("Handling the internal scope validation.");
        }
        // Execute Internal SCOPE Validation.
        JDBCPermissionBasedInternalScopeValidator scopeValidator = new JDBCPermissionBasedInternalScopeValidator();
        authorizedInternalScopes = scopeValidator.validateScope(tokReqMsgCtx);
        // Execute internal console scopes validation.
        if (IdentityUtil.isSystemRolesEnabled()) {
            RoleBasedInternalScopeValidator roleBasedInternalScopeValidator = new RoleBasedInternalScopeValidator();
            String[] roleBasedInternalConsoleScopes = roleBasedInternalScopeValidator.validateScope(tokReqMsgCtx);
            authorizedInternalScopes = (String[]) ArrayUtils.addAll(authorizedInternalScopes, roleBasedInternalConsoleScopes);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Skipping the internal scope validation as the application is not" + " configured as Management App");
        }
    }
    // Clear the internal scopes. Internal scopes should only handle in JDBCPermissionBasedInternalScopeValidator.
    // Those scopes should not send to the other scopes validators.
    // Thus remove the scopes from the tokReqMsgCtx. Will be added to the response after executing
    // the other scope validators.
    removeInternalScopes(tokReqMsgCtx);
    // Adding the authorized internal scopes to tokReqMsgCtx for any special validators to use.
    tokReqMsgCtx.setAuthorizedInternalScopes(authorizedInternalScopes);
    boolean isDropUnregisteredScopes = OAuthServerConfiguration.getInstance().isDropUnregisteredScopes();
    if (isDropUnregisteredScopes) {
        if (log.isDebugEnabled()) {
            log.debug("DropUnregisteredScopes config is enabled. Attempting to drop unregistered scopes.");
        }
        String[] filteredScopes = OAuth2Util.dropUnregisteredScopes(tokReqMsgCtx.getScope(), tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain());
        tokReqMsgCtx.setScope(filteredScopes);
    }
    boolean isValidScope = authzGrantHandler.validateScope(tokReqMsgCtx);
    if (isValidScope) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            if (ArrayUtils.isNotEmpty(tokenReqDTO.getScope())) {
                params.put("scope", Arrays.asList(tokenReqDTO.getScope()));
            }
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "OAuth scope validation is successful.", "validate-scope", null);
        }
        // Add authorized internal scopes to the request for sending in the response.
        addAuthorizedInternalScopes(tokReqMsgCtx, tokReqMsgCtx.getAuthorizedInternalScopes());
        addAllowedScopes(tokReqMsgCtx, requestedAllowedScopes.toArray(new String[0]));
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Invalid scope provided by client Id: " + tokenReqDTO.getClientId());
        }
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            if (ArrayUtils.isNotEmpty(tokenReqDTO.getScope())) {
                params.put("scope", Arrays.asList(tokenReqDTO.getScope()));
            }
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Invalid scope provided in the request.", "validate-scope", null);
        }
        tokenRespDTO = handleError(OAuthError.TokenResponse.INVALID_SCOPE, "Invalid Scope!", tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    handleTokenBinding(tokenReqDTO, grantType, tokReqMsgCtx, oAuthAppDO);
    try {
        // set the token request context to be used by downstream handlers. This is introduced as a fix for
        // IDENTITY-4111.
        OAuth2Util.setTokenRequestContext(tokReqMsgCtx);
        AuthenticatedUser authorizedUser = tokReqMsgCtx.getAuthorizedUser();
        if (authorizedUser.getAuthenticatedSubjectIdentifier() == null) {
            authorizedUser.setAuthenticatedSubjectIdentifier(getSubjectClaim(getServiceProvider(tokReqMsgCtx.getOauth2AccessTokenReqDTO()), authorizedUser));
        }
        tokenRespDTO = authzGrantHandler.issue(tokReqMsgCtx);
        if (tokenRespDTO.isError()) {
            setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
            return tokenRespDTO;
        }
    } finally {
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        // clears the token request context.
        OAuth2Util.clearTokenRequestContext();
    }
    tokenRespDTO.setCallbackURI(oAuthAppDO.getCallbackUrl());
    String[] scopes = tokReqMsgCtx.getScope();
    if (scopes != null && scopes.length > 0) {
        StringBuilder scopeString = new StringBuilder("");
        for (String scope : scopes) {
            scopeString.append(scope);
            scopeString.append(" ");
        }
        tokenRespDTO.setAuthorizedScopes(scopeString.toString().trim());
    }
    setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
    // Do not change this log format as these logs use by external applications
    if (log.isDebugEnabled()) {
        log.debug("Access token issued to client Id: " + tokenReqDTO.getClientId() + " username: " + tokReqMsgCtx.getAuthorizedUser() + " and scopes: " + tokenRespDTO.getAuthorizedScopes());
    }
    if (LoggerUtils.isDiagnosticLogsEnabled()) {
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", tokenReqDTO.getClientId());
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Access token issued for the application.", "issue-access-token", null);
    }
    if (GrantType.AUTHORIZATION_CODE.toString().equals(grantType)) {
        // Should add user attributes to the cache before building the ID token.
        addUserAttributesAgainstAccessToken(tokenReqDTO, tokenRespDTO);
    }
    if (tokReqMsgCtx.getScope() != null && OAuth2Util.isOIDCAuthzRequest(tokReqMsgCtx.getScope())) {
        if (log.isDebugEnabled()) {
            log.debug("Issuing ID token for client: " + tokenReqDTO.getClientId());
        }
        IDTokenBuilder builder = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenBuilder();
        try {
            String idToken = builder.buildIDToken(tokReqMsgCtx, tokenRespDTO);
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", tokenReqDTO.getClientId());
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "ID token issued for the application.", "issue-id-token", null);
            }
            tokenRespDTO.setIDToken(idToken);
        } catch (IDTokenValidationFailureException e) {
            log.error(e.getMessage());
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", tokenReqDTO.getClientId());
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "System error occurred.", "issue-id-token", null);
            }
            tokenRespDTO = handleError(OAuth2ErrorCodes.SERVER_ERROR, "Server Error", tokenReqDTO);
            return tokenRespDTO;
        }
    }
    if (GrantType.AUTHORIZATION_CODE.toString().equals(grantType)) {
        // Cache entry against the authorization code has no value beyond the token request.
        clearCacheEntryAgainstAuthorizationCode(getAuthorizationCode(tokenReqDTO));
    }
    return tokenRespDTO;
}
Also used : AuthorizationGrantHandler(org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationGrantHandler) HashMap(java.util.HashMap) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) ArrayList(java.util.ArrayList) OAuthClientAuthnContext(org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IDTokenBuilder(org.wso2.carbon.identity.openidconnect.IDTokenBuilder) RoleBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.RoleBasedInternalScopeValidator) OAuth2AccessTokenRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) IDTokenValidationFailureException(org.wso2.carbon.identity.oauth2.IDTokenValidationFailureException) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

JDBCPermissionBasedInternalScopeValidator (org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)2 Map (java.util.Map)2 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)2 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)2 OAuth2ScopeConsentResponse (org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse)2 Constructor (java.lang.reflect.Constructor)1 Field (java.lang.reflect.Field)1 Modifier (java.lang.reflect.Modifier)1 URLEncoder (java.net.URLEncoder)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Arrays (java.util.Arrays)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Optional (java.util.Optional)1 Set (java.util.Set)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)1