Search in sources :

Example 1 with TokenPersistenceProcessor

use of org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuthAppDAO method addOAuthApplication.

public void addOAuthApplication(OAuthAppDO consumerAppDO) throws IdentityOAuthAdminException {
    AuthenticatedUser appOwner = consumerAppDO.getAppOwner();
    int spTenantId = IdentityTenantUtil.getTenantId(appOwner.getTenantDomain());
    String userStoreDomain = appOwner.getUserStoreDomain();
    if (!isDuplicateApplication(appOwner.getUserName(), spTenantId, userStoreDomain, consumerAppDO)) {
        int appId = 0;
        try (Connection connection = IdentityDatabaseUtil.getDBConnection()) {
            try {
                String processedClientId = persistenceProcessor.getProcessedClientId(consumerAppDO.getOauthConsumerKey());
                String processedClientSecret = persistenceProcessor.getProcessedClientSecret(consumerAppDO.getOauthConsumerSecret());
                String dbProductName = connection.getMetaData().getDatabaseProductName();
                try (PreparedStatement prepStmt = connection.prepareStatement(SQLQueries.OAuthAppDAOSQLQueries.ADD_OAUTH_APP_WITH_PKCE, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "ID") })) {
                    prepStmt.setString(1, processedClientId);
                    prepStmt.setString(2, processedClientSecret);
                    prepStmt.setString(3, appOwner.getUserName());
                    prepStmt.setInt(4, spTenantId);
                    prepStmt.setString(5, userStoreDomain);
                    prepStmt.setString(6, consumerAppDO.getApplicationName());
                    prepStmt.setString(7, consumerAppDO.getOauthVersion());
                    prepStmt.setString(8, consumerAppDO.getCallbackUrl());
                    prepStmt.setString(9, consumerAppDO.getGrantTypes());
                    prepStmt.setString(10, consumerAppDO.isPkceMandatory() ? "1" : "0");
                    prepStmt.setString(11, consumerAppDO.isPkceSupportPlain() ? "1" : "0");
                    prepStmt.setLong(12, consumerAppDO.getUserAccessTokenExpiryTime());
                    prepStmt.setLong(13, consumerAppDO.getApplicationAccessTokenExpiryTime());
                    prepStmt.setLong(14, consumerAppDO.getRefreshTokenExpiryTime());
                    prepStmt.setLong(15, consumerAppDO.getIdTokenExpiryTime());
                    prepStmt.execute();
                    try (ResultSet results = prepStmt.getGeneratedKeys()) {
                        if (results.next()) {
                            appId = results.getInt(1);
                        }
                    }
                }
                // Some JDBC Drivers returns this in the result, some don't so need to check before continuing.
                if (appId == 0) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("JDBC Driver did not returning the app id of the newly created app " + consumerAppDO.getApplicationName() + ". So executing select operation to get the id");
                    }
                    appId = getAppIdByClientId(connection, consumerAppDO.getOauthConsumerKey());
                }
                addScopeValidators(connection, appId, consumerAppDO.getScopeValidators());
                // Handle OIDC Related Properties. These are persisted in IDN_OIDC_PROPERTY table.
                addServiceProviderOIDCProperties(connection, consumerAppDO, processedClientId, spTenantId);
                IdentityDatabaseUtil.commitTransaction(connection);
            } catch (SQLException e1) {
                IdentityDatabaseUtil.rollbackTransaction(connection);
                if (isDuplicateClient(e1)) {
                    String msg = "An application with the same clientId already exists.";
                    throw new IdentityOAuthClientException(Error.DUPLICATE_OAUTH_CLIENT.getErrorCode(), msg, e1);
                }
                throw handleError(String.format("Error when executing SQL to create OAuth app %s@%s ", consumerAppDO.getApplicationName(), appOwner.getTenantDomain()), e1);
            }
        } catch (SQLException e) {
            throw handleError(String.format("Error when executing SQL to create OAuth app %s@%s ", consumerAppDO.getApplicationName(), appOwner.getTenantDomain()), e);
        } catch (IdentityOAuth2Exception e) {
            throw handleError("Error occurred while processing the client id and client secret by " + "TokenPersistenceProcessor", null);
        } catch (InvalidOAuthClientException e) {
            throw handleError("Error occurred while processing client id", e);
        }
    } else {
        String msg = "An application with the same name already exists.";
        throw new IdentityOAuthClientException(Error.DUPLICATE_OAUTH_CLIENT.getErrorCode(), msg);
    }
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) IdentityOAuthClientException(org.wso2.carbon.identity.oauth.IdentityOAuthClientException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 2 with TokenPersistenceProcessor

use of org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor in project identity-inbound-auth-oauth by wso2-extensions.

the class AuthorizationCodeGrantHandlerTest method testValidateGrantException.

@Test(dataProvider = "buildErrorTokenRequestMessageContext")
public void testValidateGrantException(Object tokenRequestMessageContext, Object authzCode, String clientId, boolean pkceValid, long timestamp, String expectedError) throws Exception {
    AuthzCodeDO authzCodeDO = (AuthzCodeDO) authzCode;
    WhiteboxImpl.setInternalState(authorizationCodeGrantHandler, "cacheEnabled", true);
    OAuthCache oAuthCache = mock(OAuthCache.class);
    when(OAuthCache.getInstance()).thenReturn(oAuthCache);
    WhiteboxImpl.setInternalState(authorizationCodeGrantHandler, "oauthCache", oAuthCache);
    OAuthTokenReqMessageContext tokReqMsgCtx = (OAuthTokenReqMessageContext) tokenRequestMessageContext;
    oAuthServerConfiguration = mock(OAuthServerConfiguration.class);
    TokenPersistenceProcessor tokenPersistenceProcessor = mock(TokenPersistenceProcessor.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(oAuthServerConfiguration.getPersistenceProcessor()).thenReturn(tokenPersistenceProcessor);
    OAuthAppDAO oAuthAppDAO = mock(OAuthAppDAO.class);
    OAuthAppDO oAuthAppDO = new OAuthAppDO();
    whenNew(OAuthAppDAO.class).withNoArguments().thenReturn(oAuthAppDAO);
    when(oAuthAppDAO.getAppInformation(CLIENT_ID_VALUE)).thenReturn(oAuthAppDO);
    when(oAuthAppDAO.getAppInformation(INVALID_CLIENT)).thenThrow(new InvalidOAuthClientException("Error"));
    AppInfoCache appInfoCache = mock(AppInfoCache.class);
    when(AppInfoCache.getInstance()).thenReturn(appInfoCache);
    doNothing().when(appInfoCache).addToCache(anyString(), any(OAuthAppDO.class));
    spy(OAuth2Util.class);
    doReturn(pkceValid).when(OAuth2Util.class, "validatePKCE", anyString(), anyString(), anyString(), any(OAuthAppDO.class));
    try {
        authorizationCodeGrantHandler.validateGrant(tokReqMsgCtx);
        fail("Expected exception not thrown");
    } catch (IdentityOAuth2Exception e) {
        assertTrue(e.getMessage().contains(expectedError), "Expected error message with '" + expectedError + "'");
    }
}
Also used : OAuthAppDAO(org.wso2.carbon.identity.oauth.dao.OAuthAppDAO) AppInfoCache(org.wso2.carbon.identity.oauth.cache.AppInfoCache) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthCache(org.wso2.carbon.identity.oauth.cache.OAuthCache) OAuthTokenReqMessageContext(org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) TokenPersistenceProcessor(org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor) AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 3 with TokenPersistenceProcessor

use of org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2UtilTest method testAuthenticateClientWithHashPersistenceProcessor.

@Test(dataProvider = "AuthenticateClient")
public void testAuthenticateClientWithHashPersistenceProcessor(Object cacheResult, String clientSecretInDB, boolean expectedResult) throws Exception {
    OAuthAppDO appDO = new OAuthAppDO();
    appDO.setOauthConsumerKey(clientId);
    appDO.setOauthConsumerSecret(clientSecretInDB);
    // Mock the cache result
    AppInfoCache appInfoCache = mock(AppInfoCache.class);
    when(appInfoCache.getValueFromCache(clientId)).thenReturn((OAuthAppDO) cacheResult);
    mockStatic(AppInfoCache.class);
    when(AppInfoCache.getInstance()).thenReturn(appInfoCache);
    // Mock the DB result
    OAuthAppDAO oAuthAppDAO = mock(OAuthAppDAO.class);
    when(oAuthAppDAO.getAppInformation(clientId)).thenReturn(appDO);
    PowerMockito.whenNew(OAuthAppDAO.class).withNoArguments().thenReturn(oAuthAppDAO);
    TokenPersistenceProcessor hashingProcessor = mock(HashingPersistenceProcessor.class);
    when(hashingProcessor.getProcessedClientSecret(clientSecret)).thenReturn(clientSecret);
    when(oauthServerConfigurationMock.isClientSecretHashEnabled()).thenReturn(true);
    when(oauthServerConfigurationMock.getPersistenceProcessor()).thenReturn(hashingProcessor);
    assertEquals(OAuth2Util.authenticateClient(clientId, clientSecret), expectedResult);
}
Also used : AppInfoCache(org.wso2.carbon.identity.oauth.cache.AppInfoCache) OAuthAppDAO(org.wso2.carbon.identity.oauth.dao.OAuthAppDAO) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) TokenPersistenceProcessor(org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 4 with TokenPersistenceProcessor

use of org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor in project identity-inbound-auth-oauth by wso2-extensions.

the class AuthorizationCodeGrantHandlerTest method testValidateGrant.

@Test(dataProvider = "BuildTokenRequestMessageContext")
public void testValidateGrant(Object tokenRequestMessageContext, Object authzCode, boolean cacheEnabled, boolean debugEnabled, long timestamp, boolean expectedResult) throws Exception {
    AuthzCodeDO authzCodeDO = (AuthzCodeDO) authzCode;
    WhiteboxImpl.setInternalState(authorizationCodeGrantHandler, "cacheEnabled", cacheEnabled);
    OAuthCache oAuthCache = mock(OAuthCache.class);
    when(OAuthCache.getInstance()).thenReturn(oAuthCache);
    if (cacheEnabled) {
        WhiteboxImpl.setInternalState(authorizationCodeGrantHandler, "oauthCache", oAuthCache);
    }
    OAuthTokenReqMessageContext tokReqMsgCtx = (OAuthTokenReqMessageContext) tokenRequestMessageContext;
    oAuthServerConfiguration = mock(OAuthServerConfiguration.class);
    TokenPersistenceProcessor tokenPersistenceProcessor = mock(TokenPersistenceProcessor.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(oAuthServerConfiguration.getPersistenceProcessor()).thenReturn(tokenPersistenceProcessor);
    OAuthAppDAO oAuthAppDAO = mock(OAuthAppDAO.class);
    OAuthAppDO oAuthAppDO = new OAuthAppDO();
    whenNew(OAuthAppDAO.class).withNoArguments().thenReturn(oAuthAppDAO);
    when(oAuthAppDAO.getAppInformation(anyString())).thenReturn(oAuthAppDO);
    AppInfoCache appInfoCache = mock(AppInfoCache.class);
    when(AppInfoCache.getInstance()).thenReturn(appInfoCache);
    doNothing().when(appInfoCache).addToCache(anyString(), any(OAuthAppDO.class));
    assertEquals(authorizationCodeGrantHandler.validateGrant(tokReqMsgCtx), expectedResult);
}
Also used : OAuthAppDAO(org.wso2.carbon.identity.oauth.dao.OAuthAppDAO) AppInfoCache(org.wso2.carbon.identity.oauth.cache.AppInfoCache) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) OAuthCache(org.wso2.carbon.identity.oauth.cache.OAuthCache) OAuthTokenReqMessageContext(org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) TokenPersistenceProcessor(org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor) AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 5 with TokenPersistenceProcessor

use of org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor in project identity-inbound-auth-oauth by wso2-extensions.

the class OIDCLogoutServletTest method testDoGet.

@Test(dataProvider = "provideDataForTestDoGet")
public void testDoGet(Object cookie, boolean sessionExists, String redirectUrl, String expected, String consent, String sessionDataKey, boolean skipUserConsent, String idTokenHint, boolean isJWTSignedWithSPKey, String postLogoutUrl, Object flowStatus) throws Exception {
    TestUtil.startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    mockStatic(OIDCSessionManagementUtil.class);
    when(OIDCSessionManagementUtil.handleAlreadyLoggedOutSessionsGracefully()).thenReturn(false);
    when(OIDCSessionManagementUtil.getOPBrowserStateCookie(request)).thenReturn((Cookie) cookie);
    when(OIDCSessionManagementUtil.getErrorPageURL(anyString(), anyString())).thenReturn(redirectUrl);
    mockStatic(OIDCSessionManager.class);
    when(OIDCSessionManagementUtil.getSessionManager()).thenReturn(oidcSessionManager);
    when(oidcSessionManager.sessionExists(OPBROWSER_STATE, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)).thenReturn(sessionExists);
    when(request.getParameter("consent")).thenReturn(consent);
    when(request.getHeaderNames()).thenReturn(Collections.enumeration(Arrays.asList(new String[] { "cookie" })));
    when(request.getHeader("COOKIE")).thenReturn("opbs");
    when(request.getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS)).thenReturn(flowStatus);
    doThrow(new ServletException()).when(commonAuthenticationHandler).doPost(request, response);
    when(request.getSession()).thenReturn(httpSession);
    when(httpSession.getMaxInactiveInterval()).thenReturn(2);
    mockStatic(IdentityConfigParser.class);
    when(IdentityConfigParser.getInstance()).thenReturn(identityConfigParser);
    when(request.getParameter("sessionDataKey")).thenReturn(sessionDataKey);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(oAuthServerConfiguration.getOpenIDConnectSkipLogoutConsentConfig()).thenReturn(skipUserConsent);
    when(request.getParameter("id_token_hint")).thenReturn(idTokenHint);
    when(OIDCSessionManagementUtil.removeOPBrowserStateCookie(any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn((Cookie) cookie);
    when(OIDCSessionManagementUtil.getOIDCLogoutConsentURL()).thenReturn(redirectUrl);
    when(OIDCSessionManagementUtil.getOIDCLogoutURL()).thenReturn(redirectUrl);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(TENANT_ID);
    when(IdentityTenantUtil.getTenantDomain(TENANT_ID)).thenReturn(SUPER_TENANT_DOMAIN_NAME);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(oAuthServerConfiguration.isJWTSignedWithSPKey()).thenReturn(isJWTSignedWithSPKey);
    mockStatic(KeyStoreManager.class);
    when(KeyStoreManager.getInstance(TENANT_ID)).thenReturn(keyStoreManager);
    when(keyStoreManager.getDefaultPublicKey()).thenReturn(TestUtil.getPublicKey(TestUtil.loadKeyStoreFromFileSystem(TestUtil.getFilePath("wso2carbon.jks"), "wso2carbon", "JKS"), "wso2carbon"));
    mockStatic(OIDCSessionManagementComponentServiceHolder.class);
    when(OIDCSessionManagementComponentServiceHolder.getApplicationMgtService()).thenReturn(mockedApplicationManagementService);
    when(mockedApplicationManagementService.getServiceProviderNameByClientId(anyString(), anyString(), anyString())).thenReturn("SP1");
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(oAuthServerConfiguration.getPersistenceProcessor()).thenReturn(tokenPersistenceProcessor);
    when(tokenPersistenceProcessor.getProcessedClientId(anyString())).thenAnswer(invocation -> invocation.getArguments()[0]);
    when(request.getParameter("post_logout_redirect_uri")).thenReturn(postLogoutUrl);
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenAnswer(invocationOnMock -> dataSource.getConnection());
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getAppInformationByClientId(anyString())).thenCallRealMethod();
    when(OAuth2Util.getTenantDomainOfOauthApp(anyString())).thenReturn("wso2.com");
    when(OAuth2Util.getTenantDomainOfOauthApp(any(oAuthAppDO.getClass()))).thenReturn("wso2.com");
    when(keyStoreManager.getKeyStore(anyString())).thenReturn(TestUtil.loadKeyStoreFromFileSystem(TestUtil.getFilePath("wso2carbon.jks"), "wso2carbon", "JKS"));
    mockServiceURLBuilder(OIDCSessionConstants.OIDCEndpoints.OIDC_LOGOUT_ENDPOINT);
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    mockStatic(OIDCSessionDataCache.class);
    when(OIDCSessionDataCache.getInstance()).thenReturn(oidcSessionDataCache);
    OIDCSessionDataCacheKey opbsKey = mock(OIDCSessionDataCacheKey.class);
    OIDCSessionDataCacheKey sessionIdKey = mock(OIDCSessionDataCacheKey.class);
    when(opbsKey.getSessionDataId()).thenReturn(OPBROWSER_STATE);
    when(sessionIdKey.getSessionDataId()).thenReturn(sessionDataKey);
    when(OIDCSessionDataCache.getInstance().getValueFromCache(opbsKey)).thenReturn(opbsCacheEntry);
    when(OIDCSessionDataCache.getInstance().getValueFromCache(sessionIdKey)).thenReturn(sessionIdCacheEntry);
    ConcurrentMap<String, String> paramMap = new ConcurrentHashMap<>();
    paramMap.put(OIDCSessionConstants.OIDC_CACHE_CLIENT_ID_PARAM, CLIENT_ID_VALUE);
    paramMap.put(OIDCSessionConstants.OIDC_CACHE_TENANT_DOMAIN_PARAM, SUPER_TENANT_DOMAIN_NAME);
    when(opbsCacheEntry.getParamMap()).thenReturn(paramMap);
    when(sessionIdCacheEntry.getParamMap()).thenReturn(paramMap);
    logoutServlet.doGet(request, response);
    verify(response).sendRedirect(captor.capture());
    assertTrue(captor.getValue().contains(expected));
}
Also used : ServletException(javax.servlet.ServletException) HttpServletRequest(javax.servlet.http.HttpServletRequest) OIDCSessionDataCacheKey(org.wso2.carbon.identity.oidc.session.cache.OIDCSessionDataCacheKey) HttpServletResponse(javax.servlet.http.HttpServletResponse) Matchers.anyString(org.mockito.Matchers.anyString) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)6 Connection (java.sql.Connection)5 PreparedStatement (java.sql.PreparedStatement)5 SQLException (java.sql.SQLException)5 TokenPersistenceProcessor (org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor)5 Test (org.testng.annotations.Test)4 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)4 ResultSet (java.sql.ResultSet)3 BeforeTest (org.testng.annotations.BeforeTest)3 AppInfoCache (org.wso2.carbon.identity.oauth.cache.AppInfoCache)3 OAuthAppDAO (org.wso2.carbon.identity.oauth.dao.OAuthAppDAO)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)2 OAuthCache (org.wso2.carbon.identity.oauth.cache.OAuthCache)2 InvalidOAuthClientException (org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)2 OAuthServerConfiguration (org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration)2 AuthzCodeDO (org.wso2.carbon.identity.oauth2.model.AuthzCodeDO)2 OAuthTokenReqMessageContext (org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext)2 ArrayList (java.util.ArrayList)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1