Search in sources :

Example 1 with OAuth2ScopeService

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

the class ScopesApiServiceImplTest method testUpdateScope.

@Test(dataProvider = "BuildUpdateScope")
public void testUpdateScope(Response.Status expectation, Throwable throwable) throws Exception {
    ScopeToUpdateDTO scopeToUpdateDTO = new ScopeToUpdateDTO();
    scopeToUpdateDTO.setDescription("some description");
    scopeToUpdateDTO.setBindings(Collections.<String>emptyList());
    if (Response.Status.OK.equals(expectation)) {
        when(ScopeUtils.getScopeDTO(any(Scope.class))).thenReturn(any(ScopeDTO.class));
        assertEquals(scopesApiService.updateScope(scopeToUpdateDTO, someScopeName).getStatus(), Response.Status.OK.getStatusCode(), "Error occurred while updating scopes");
    } else if (Response.Status.BAD_REQUEST.equals(expectation)) {
        when(oAuth2ScopeService.updateScope(any(Scope.class))).thenThrow(IdentityOAuth2ScopeClientException.class);
        callRealMethod();
        try {
            scopesApiService.updateScope(scopeToUpdateDTO, someScopeName);
        } catch (ScopeEndpointException e) {
            assertEquals(e.getResponse().getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), "Cannot find HTTP Response, Bad Request in Case of " + "IdentityOAuth2ScopeClientException");
            assertEquals(((ErrorDTO) (e.getResponse().getEntity())).getMessage(), Response.Status.BAD_REQUEST.getReasonPhrase(), "Cannot find appropriate error message " + "for HTTP Response, Bad Request");
        } finally {
            reset(oAuth2ScopeService);
        }
    } else if (Response.Status.NOT_FOUND.equals(expectation)) {
        ((IdentityOAuth2ScopeException) throwable).setErrorCode(Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_NOT_FOUND_SCOPE.getCode());
        when(oAuth2ScopeService.updateScope(any(Scope.class))).thenThrow(throwable);
        callRealMethod();
        try {
            scopesApiService.updateScope(scopeToUpdateDTO, someScopeName);
        } catch (ScopeEndpointException e) {
            assertEquals(e.getResponse().getStatus(), Response.Status.NOT_FOUND.getStatusCode(), "Cannot find HTTP Response, Not Found in Case of " + "IdentityOAuth2ScopeClientException");
            assertEquals(((ErrorDTO) (e.getResponse().getEntity())).getMessage(), Response.Status.NOT_FOUND.getReasonPhrase(), "Cannot find appropriate error message " + "for HTTP Response, Not Found");
        } finally {
            reset(oAuth2ScopeService);
        }
    } else if (Response.Status.INTERNAL_SERVER_ERROR.equals(expectation)) {
        when(oAuth2ScopeService.updateScope(any(Scope.class))).thenThrow(IdentityOAuth2ScopeException.class);
        callRealMethod();
        try {
            scopesApiService.updateScope(scopeToUpdateDTO, someScopeName);
        } catch (ScopeEndpointException e) {
            assertEquals(e.getResponse().getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "Cannot find HTTP Response, Internal Server Error in case of " + "IdentityOAuth2ScopeException");
            assertNull(e.getResponse().getEntity(), "Do not include error message in case of " + "Server Exception");
        } finally {
            reset(oAuth2ScopeService);
        }
    }
}
Also used : ScopeEndpointException(org.wso2.carbon.identity.oauth.scope.endpoint.exceptions.ScopeEndpointException) Scope(org.wso2.carbon.identity.oauth2.bean.Scope) ScopeDTO(org.wso2.carbon.identity.oauth.scope.endpoint.dto.ScopeDTO) ErrorDTO(org.wso2.carbon.identity.oauth.scope.endpoint.dto.ErrorDTO) ScopeToUpdateDTO(org.wso2.carbon.identity.oauth.scope.endpoint.dto.ScopeToUpdateDTO) IdentityOAuth2ScopeClientException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeClientException) IdentityOAuth2ScopeException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 2 with OAuth2ScopeService

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

the class OAuth2ServiceComponent method activate.

protected void activate(ComponentContext context) {
    try {
        if (OAuth2ServiceComponentHolder.getInstance().getScopeClaimMappingDAO() == null) {
            OAuth2ServiceComponentHolder.getInstance().setScopeClaimMappingDAO(new ScopeClaimMappingDAOImpl());
        }
        loadScopeConfigFile();
        loadOauthScopeBinding();
        int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        boolean isRecordExist = OAuthTokenPersistenceFactory.getInstance().getScopeClaimMappingDAO().hasScopesPopulated(tenantId);
        if (!isRecordExist) {
            OAuth2Util.initiateOIDCScopes(tenantId);
        }
        TenantCreationEventListener scopeTenantMgtListener = new TenantCreationEventListener();
        bundleContext = context.getBundleContext();
        // Registering TenantCreationEventListener
        ServiceRegistration scopeTenantMgtListenerSR = bundleContext.registerService(TenantMgtListener.class.getName(), scopeTenantMgtListener, null);
        if (scopeTenantMgtListenerSR != null) {
            if (log.isDebugEnabled()) {
                log.debug(" TenantMgtListener is registered");
            }
        } else {
            log.error("TenantMgtListener could not be registered");
        }
        // iniating oauth scopes
        OAuth2Util.initiateOAuthScopePermissionsBindings(tenantId);
        // exposing server configuration as a service
        OAuthServerConfiguration oauthServerConfig = OAuthServerConfiguration.getInstance();
        bundleContext.registerService(OAuthServerConfiguration.class.getName(), oauthServerConfig, null);
        OAuth2TokenValidationService tokenValidationService = new OAuth2TokenValidationService();
        bundleContext.registerService(OAuth2TokenValidationService.class.getName(), tokenValidationService, null);
        OAuthClientAuthnService clientAuthnService = new OAuthClientAuthnService();
        bundleContext.registerService(OAuthClientAuthnService.class.getName(), clientAuthnService, null);
        BasicAuthClientAuthenticator basicAuthClientAuthenticator = new BasicAuthClientAuthenticator();
        bundleContext.registerService(OAuthClientAuthenticator.class.getName(), basicAuthClientAuthenticator, null);
        PublicClientAuthenticator publicClientAuthenticator = new PublicClientAuthenticator();
        bundleContext.registerService(OAuthClientAuthenticator.class.getName(), publicClientAuthenticator, null);
        // Register cookie based access token binder.
        CookieBasedTokenBinder cookieBasedTokenBinder = new CookieBasedTokenBinder();
        bundleContext.registerService(TokenBinderInfo.class.getName(), cookieBasedTokenBinder, null);
        // SSO session based access token binder.
        SSOSessionBasedTokenBinder ssoSessionBasedTokenBinder = new SSOSessionBasedTokenBinder();
        bundleContext.registerService(TokenBinderInfo.class.getName(), ssoSessionBasedTokenBinder, null);
        if (log.isDebugEnabled()) {
            log.debug("Identity OAuth bundle is activated");
        }
        if (OAuth2ServiceComponentHolder.getKeyIDProvider() == null) {
            KeyIDProvider defaultKeyIDProvider = new DefaultKeyIDProviderImpl();
            OAuth2ServiceComponentHolder.setKeyIDProvider(defaultKeyIDProvider);
            if (log.isDebugEnabled()) {
                log.debug("Key ID Provider " + DefaultKeyIDProviderImpl.class.getSimpleName() + " registered as the default Key ID Provider implementation.");
            }
        }
        ServiceRegistration tenantMgtListenerSR = bundleContext.registerService(TenantMgtListener.class.getName(), new OAuthTenantMgtListenerImpl(), null);
        if (tenantMgtListenerSR != null) {
            if (log.isDebugEnabled()) {
                log.debug("OAuth - TenantMgtListener registered.");
            }
        } else {
            log.error("OAuth - TenantMgtListener could not be registered.");
        }
        ServiceRegistration userStoreConfigEventSR = bundleContext.registerService(UserStoreConfigListener.class.getName(), new OAuthUserStoreConfigListenerImpl(), null);
        if (userStoreConfigEventSR != null) {
            if (log.isDebugEnabled()) {
                log.debug("OAuth - UserStoreConfigListener registered.");
            }
        } else {
            log.error("OAuth - UserStoreConfigListener could not be registered.");
        }
        ServiceRegistration oauthApplicationMgtListenerSR = bundleContext.registerService(ApplicationMgtListener.class.getName(), new OAuthApplicationMgtListener(), null);
        if (oauthApplicationMgtListenerSR != null) {
            if (log.isDebugEnabled()) {
                log.debug("OAuth - ApplicationMgtListener registered.");
            }
        } else {
            log.error("OAuth - ApplicationMgtListener could not be registered.");
        }
        // PKCE enabled by default.
        OAuth2ServiceComponentHolder.setPkceEnabled(true);
        // Register device auth service.
        ServiceRegistration deviceAuthService = bundleContext.registerService(DeviceAuthService.class.getName(), new DeviceAuthServiceImpl(), null);
        if (deviceAuthService != null) {
            if (log.isDebugEnabled()) {
                log.debug("DeviceAuthService registered.");
            }
        } else {
            log.error("DeviceAuthService could not be registered.");
        }
        // Register the default OpenIDConnect claim filter
        bundleContext.registerService(OpenIDConnectClaimFilter.class, new OpenIDConnectClaimFilterImpl(), null);
        if (log.isDebugEnabled()) {
            log.debug("Default OpenIDConnect Claim filter registered successfully.");
        }
        bundleContext.registerService(AbstractEventHandler.class.getName(), new TokenBindingExpiryEventHandler(), null);
        if (log.isDebugEnabled()) {
            log.debug("TokenBindingExpiryEventHandler is successfully registered.");
        }
        // Registering OAuth2Service as a OSGIService
        bundleContext.registerService(OAuth2Service.class.getName(), new OAuth2Service(), null);
        // Registering OAuth2ScopeService as a OSGIService
        bundleContext.registerService(OAuth2ScopeService.class.getName(), new OAuth2ScopeService(), null);
    // Note : DO NOT add any activation related code below this point,
    // to make sure the server doesn't start up if any activation failures occur
    } catch (Throwable e) {
        String errMsg = "Error while activating OAuth2ServiceComponent.";
        log.error(errMsg, e);
        throw new RuntimeException(errMsg, e);
    }
    if (checkAudienceEnabled()) {
        if (log.isDebugEnabled()) {
            log.debug("OAuth - OIDC audiences enabled.");
        }
        OAuth2ServiceComponentHolder.setAudienceEnabled(true);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("OAuth - OIDC audiences disabled.");
        }
        OAuth2ServiceComponentHolder.setAudienceEnabled(false);
    }
    if (checkIDPIdColumnAvailable()) {
        if (log.isDebugEnabled()) {
            log.debug("IDP_ID column is available in all relevant tables. " + "Setting isIDPIdColumnEnabled to true.");
        }
        OAuth2ServiceComponentHolder.setIDPIdColumnEnabled(true);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("IDP_ID column is not available in all relevant tables. " + "Setting isIDPIdColumnEnabled to false.");
        }
        OAuth2ServiceComponentHolder.setIDPIdColumnEnabled(false);
    }
}
Also used : TokenBindingExpiryEventHandler(org.wso2.carbon.identity.oauth2.token.bindings.handlers.TokenBindingExpiryEventHandler) KeyIDProvider(org.wso2.carbon.identity.oauth2.keyidprovider.KeyIDProvider) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) TokenBinderInfo(org.wso2.carbon.identity.oauth.common.token.bindings.TokenBinderInfo) ApplicationMgtListener(org.wso2.carbon.identity.application.mgt.listener.ApplicationMgtListener) OAuth2ScopeService(org.wso2.carbon.identity.oauth2.OAuth2ScopeService) TenantMgtListener(org.wso2.carbon.stratos.common.listeners.TenantMgtListener) CookieBasedTokenBinder(org.wso2.carbon.identity.oauth2.token.bindings.impl.CookieBasedTokenBinder) SSOSessionBasedTokenBinder(org.wso2.carbon.identity.oauth2.token.bindings.impl.SSOSessionBasedTokenBinder) ServiceRegistration(org.osgi.framework.ServiceRegistration) OAuthClientAuthenticator(org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthenticator) OAuth2Service(org.wso2.carbon.identity.oauth2.OAuth2Service) OAuthClientAuthnService(org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthnService) DefaultKeyIDProviderImpl(org.wso2.carbon.identity.oauth2.keyidprovider.DefaultKeyIDProviderImpl) UserStoreConfigListener(org.wso2.carbon.identity.user.store.configuration.listener.UserStoreConfigListener) TenantCreationEventListener(org.wso2.carbon.identity.oauth2.listener.TenantCreationEventListener) PublicClientAuthenticator(org.wso2.carbon.identity.oauth2.client.authentication.PublicClientAuthenticator) BasicAuthClientAuthenticator(org.wso2.carbon.identity.oauth2.client.authentication.BasicAuthClientAuthenticator) ScopeClaimMappingDAOImpl(org.wso2.carbon.identity.openidconnect.dao.ScopeClaimMappingDAOImpl) OpenIDConnectClaimFilterImpl(org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilterImpl) DeviceAuthService(org.wso2.carbon.identity.oauth2.device.api.DeviceAuthService) AbstractEventHandler(org.wso2.carbon.identity.event.handler.AbstractEventHandler) OAuth2TokenValidationService(org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService) DeviceAuthServiceImpl(org.wso2.carbon.identity.oauth2.device.api.DeviceAuthServiceImpl)

Example 3 with OAuth2ScopeService

use of org.wso2.carbon.identity.oauth2.OAuth2ScopeService 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 OAuth2ScopeService

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

the class OAuth2AuthzEndpointTest method mockEndpointUtil.

private void mockEndpointUtil(boolean isConsentMgtEnabled) throws Exception {
    spy(EndpointUtil.class);
    doReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME).when(EndpointUtil.class, "getSPTenantDomainFromClientId", anyString());
    doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
    doReturn(oAuthServerConfiguration).when(EndpointUtil.class, "getOAuthServerConfiguration");
    doReturn(USER_CONSENT_URL).when(EndpointUtil.class, "getUserConsentURL", any(OAuth2Parameters.class), anyString(), anyString(), anyBoolean(), any(OAuthMessage.class));
    doReturn(LOGIN_PAGE_URL).when(EndpointUtil.class, "getLoginPageURL", anyString(), anyString(), anyBoolean(), anyBoolean(), anySet(), anyMap(), any());
    doReturn(requestObjectService).when(EndpointUtil.class, "getRequestObjectService");
    EndpointUtil.setOAuthAdminService(oAuthAdminService);
    EndpointUtil.setOAuth2ScopeService(oAuth2ScopeService);
    // TODO: Remove mocking consentUtil and test the consent flow as well
    // https://github.com/wso2/product-is/issues/2679
    SSOConsentService ssoConsentService = mock(SSOConsentService.class);
    when(ssoConsentService.getConsentRequiredClaimsWithExistingConsents(any(ServiceProvider.class), any(AuthenticatedUser.class))).thenReturn(new ConsentClaimsData());
    when(ssoConsentService.getConsentRequiredClaimsWithoutExistingConsents(any(ServiceProvider.class), any(AuthenticatedUser.class))).thenReturn(new ConsentClaimsData());
    when(ssoConsentService.isSSOConsentManagementEnabled(any())).thenReturn(isConsentMgtEnabled);
    doReturn(ssoConsentService).when(EndpointUtil.class, "getSSOConsentService");
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuthMessage(org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ConsentClaimsData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ConsentClaimsData) SSOConsentService(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.SSOConsentService) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 5 with OAuth2ScopeService

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

the class ScopesApiServiceImplTest method testRegisterScope.

@Test(dataProvider = "BuildRegisterScope")
public void testRegisterScope(Response.Status expectation, Throwable throwable) throws Exception {
    ScopeDTO scopeDTO = new ScopeDTO();
    scopeDTO.setDescription("some description");
    scopeDTO.setBindings(Collections.<String>emptyList());
    if (Response.Status.OK.equals(expectation)) {
        when(oAuth2ScopeService.registerScope(any(Scope.class))).thenReturn(any(Scope.class));
        assertEquals(scopesApiService.registerScope(scopeDTO).getStatus(), Response.Status.CREATED.getStatusCode(), "Error occurred while registering scopes");
    } else if (Response.Status.BAD_REQUEST.equals(expectation)) {
        when(oAuth2ScopeService.registerScope(any(Scope.class))).thenThrow(throwable);
        callRealMethod();
        try {
            scopesApiService.registerScope(scopeDTO);
        } catch (ScopeEndpointException e) {
            assertEquals(e.getResponse().getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), "Cannot find HTTP Response, Bad Request in Case of " + "IdentityOAuth2ScopeClientException");
            assertEquals(((ErrorDTO) (e.getResponse().getEntity())).getMessage(), Response.Status.BAD_REQUEST.getReasonPhrase(), "Cannot find appropriate error message " + "for HTTP Response, Bad Request");
        } finally {
            reset(oAuth2ScopeService);
        }
    } else if (Response.Status.CONFLICT.equals(expectation)) {
        ((IdentityOAuth2ScopeException) throwable).setErrorCode(Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_CONFLICT_REQUEST_EXISTING_SCOPE.getCode());
        when(oAuth2ScopeService.registerScope(any(Scope.class))).thenThrow(throwable);
        callRealMethod();
        try {
            scopesApiService.registerScope(scopeDTO);
        } catch (ScopeEndpointException e) {
            assertEquals(e.getResponse().getStatus(), Response.Status.CONFLICT.getStatusCode(), "Cannot find HTTP Response, Conflict in Case of " + "IdentityOAuth2ScopeClientException");
            assertEquals(((ErrorDTO) (e.getResponse().getEntity())).getMessage(), Response.Status.CONFLICT.getReasonPhrase(), "Cannot find appropriate error message " + "for HTTP Response, Conflict");
        } finally {
            reset(oAuth2ScopeService);
        }
    } else if (Response.Status.INTERNAL_SERVER_ERROR.equals(expectation)) {
        when(oAuth2ScopeService.registerScope(any(Scope.class))).thenThrow(IdentityOAuth2ScopeException.class);
        callRealMethod();
        try {
            scopesApiService.registerScope(scopeDTO);
        } catch (ScopeEndpointException e) {
            assertEquals(e.getResponse().getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "Cannot find HTTP Response, Internal Server Error in case of " + "IdentityOAuth2ScopeException");
            assertNull(e.getResponse().getEntity(), "Do not include error message in case of " + "Server Exception");
        } finally {
            reset(oAuth2ScopeService);
        }
    }
}
Also used : ScopeEndpointException(org.wso2.carbon.identity.oauth.scope.endpoint.exceptions.ScopeEndpointException) Scope(org.wso2.carbon.identity.oauth2.bean.Scope) ScopeDTO(org.wso2.carbon.identity.oauth.scope.endpoint.dto.ScopeDTO) ErrorDTO(org.wso2.carbon.identity.oauth.scope.endpoint.dto.ErrorDTO) IdentityOAuth2ScopeException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Aggregations

PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 Test (org.testng.annotations.Test)3 Scope (org.wso2.carbon.identity.oauth2.bean.Scope)3 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)3 SSOConsentService (org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.SSOConsentService)2 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)2 OAuthServerConfiguration (org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration)2 OAuth2ScopeService (org.wso2.carbon.identity.oauth2.OAuth2ScopeService)2 OAuth2Service (org.wso2.carbon.identity.oauth2.OAuth2Service)2 OAuth2TokenValidationService (org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService)2 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)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 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1