diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/jwks/JwksEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/jwks/JwksEndpoint.java index 28e8d1f3ee6..b193b1e2035 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/jwks/JwksEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/jwks/JwksEndpoint.java @@ -30,15 +30,15 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; +import org.wso2.carbon.identity.core.IdentityKeyStoreResolver; +import org.wso2.carbon.identity.core.util.IdentityKeyStoreResolverConstants; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.common.OAuthConstants; import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.util.OAuth2Util; -import org.wso2.carbon.utils.security.KeystoreUtils; import java.security.KeyStore; import java.security.cert.Certificate; @@ -79,21 +79,22 @@ public String jwks() { try { final KeyStore keystore; - List certificateInfoList = new ArrayList<>(); + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) { - KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID); - keystore = keyStoreManager.getPrimaryKeyStore(); + keystore = IdentityKeyStoreResolver.getInstance().getKeyStore( + tenantDomain, IdentityKeyStoreResolverConstants.InboundProtocol.OAUTH); } else { try { int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); IdentityTenantUtil.initializeRegistry(tenantId); FrameworkUtils.startTenantFlow(tenantDomain); - KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId); - keystore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain)); + keystore = IdentityKeyStoreResolver.getInstance().getKeyStore( + tenantDomain, IdentityKeyStoreResolverConstants.InboundProtocol.OAUTH); } finally { FrameworkUtils.endTenantFlow(); } } + List certificateInfoList = new ArrayList<>(); Enumeration enumeration = keystore.aliases(); while (enumeration.hasMoreElements()) { String alias = (String) enumeration.nextElement(); @@ -250,16 +251,6 @@ private String logAndReturnError(String errorMesage, Exception e) { return errorMesage; } - /** - * This method generates the key store file name from the Domain Name. - * - * @return key store file name - */ - private String generateKSNameFromDomainName(String tenantDomain) { - - return KeystoreUtils.getKeyStoreFileLocation(tenantDomain); - } - /** * This method generates the base64 encoded certificate list from a Certificate array. * diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/jwks/JwksEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/jwks/JwksEndpointTest.java index 7eb38165df0..88fc33e620b 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/jwks/JwksEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/jwks/JwksEndpointTest.java @@ -31,9 +31,9 @@ import org.testng.annotations.Test; import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.base.ServerConfiguration; -import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; +import org.wso2.carbon.identity.core.IdentityKeyStoreResolver; +import org.wso2.carbon.identity.core.util.IdentityKeyStoreResolverConstants; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.common.OAuthConstants; @@ -44,7 +44,6 @@ import org.wso2.carbon.identity.oauth2.keyidprovider.DefaultKeyIDProviderImpl; import org.wso2.carbon.identity.oauth2.util.OAuth2Util; import org.wso2.carbon.utils.CarbonUtils; -import org.wso2.carbon.utils.security.KeystoreUtils; import java.io.FileInputStream; import java.lang.reflect.Field; @@ -58,7 +57,6 @@ import java.util.Map; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mockStatic; @@ -69,9 +67,6 @@ @Listeners(MockitoTestNGListener.class) public class JwksEndpointTest { - @Mock - ServerConfiguration serverConfiguration; - @Mock OAuthServerConfiguration mockOAuthServerConfiguration; @@ -79,7 +74,7 @@ public class JwksEndpointTest { TokenPersistenceProcessor tokenPersistenceProcessor; @Mock - KeyStoreManager mockKeyStoreManager; + IdentityKeyStoreResolver mockIdentityKeyStoreResolver; private static final String CERT_THUMB_PRINT = "generatedCertThrumbPrint"; private static final String ALG = "RS256"; @@ -149,22 +144,16 @@ public void testJwks(String tenantDomain, int tenantId) throws Exception { OAuthServerConfiguration.class); MockedStatic carbonUtils = mockStatic(CarbonUtils.class); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); - MockedStatic keystoreUtils = mockStatic(KeystoreUtils.class);) { + MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class);) { - Path keystorePath = - Paths.get(System.getProperty(CarbonBaseConstants.CARBON_HOME), "repository", "resources", - "security", "wso2carbon.jks"); - keystoreUtils.when(() -> KeystoreUtils.getKeyStoreFileLocation("foo.com")).thenReturn("foo-com.jks"); mockOAuthServerConfiguration(oAuthServerConfiguration); // When the OAuth2Util is mocked, OAuthServerConfiguration instance should be available. try (MockedStatic oAuth2Util = mockStatic(OAuth2Util.class); - MockedStatic keyStoreManager = mockStatic(KeyStoreManager.class); + MockedStatic identityKeyStoreResolver = + mockStatic(IdentityKeyStoreResolver.class); MockedStatic identityUtil = mockStatic(IdentityUtil.class)) { - carbonUtils.when(CarbonUtils::getServerConfiguration).thenReturn(serverConfiguration); - ThreadLocal> threadLocalProperties = new ThreadLocal() { protected Map initialValue() { @@ -218,11 +207,16 @@ protected Map initialValue() { .thenReturn("YmUwN2EzOGI3ZTI0Y2NiNTNmZWFlZjI5Mm" + "VjZjdjZTYzZjI0M2MxNDQ1YjQwNjI3NjYyZmZlYzkwNzY0YjU4NQ"); - keyStoreManager.when(() -> KeyStoreManager.getInstance(anyInt())).thenReturn(mockKeyStoreManager); - lenient().when(mockKeyStoreManager.getKeyStore("foo-com.jks")).thenReturn( - getKeyStoreFromFile("foo-com.jks", "foo.com")); - lenient().when(mockKeyStoreManager.getPrimaryKeyStore()).thenReturn( - getKeyStoreFromFile("wso2carbon.jks", "wso2carbon")); + identityKeyStoreResolver.when(() -> IdentityKeyStoreResolver.getInstance()) + .thenReturn(mockIdentityKeyStoreResolver); + + lenient().when(mockIdentityKeyStoreResolver + .getKeyStore("carbon.super", IdentityKeyStoreResolverConstants.InboundProtocol.OAUTH)) + .thenReturn(getKeyStoreFromFile("wso2carbon.jks", "wso2carbon")); + lenient().when(mockIdentityKeyStoreResolver + .getKeyStore("foo.com", IdentityKeyStoreResolverConstants.InboundProtocol.OAUTH)) + .thenReturn(getKeyStoreFromFile("foo-com.jks", "foo.com")); + identityUtil.when(() -> IdentityUtil.getProperty(ENABLE_X5C_IN_RESPONSE)).thenReturn("true"); String result = jwksEndpoint.jwks(); diff --git a/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/authcontext/JWTTokenGenerator.java b/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/authcontext/JWTTokenGenerator.java index e370e2021fd..db4d6a5f989 100644 --- a/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/authcontext/JWTTokenGenerator.java +++ b/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/authcontext/JWTTokenGenerator.java @@ -31,11 +31,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; -import org.wso2.carbon.identity.base.IdentityException; +import org.wso2.carbon.identity.core.IdentityKeyStoreResolver; import org.wso2.carbon.identity.core.util.IdentityCoreConstants; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.core.util.IdentityKeyStoreResolverConstants; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException; import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; @@ -60,10 +59,8 @@ import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.carbon.utils.security.KeystoreUtils; import java.security.Key; -import java.security.KeyStore; import java.security.MessageDigest; import java.security.cert.Certificate; import java.security.interfaces.RSAPrivateKey; @@ -72,12 +69,10 @@ import java.util.Calendar; import java.util.Date; import java.util.List; -import java.util.Map; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; /** * This class represents the JSON Web Token generator. @@ -105,9 +100,6 @@ public class JWTTokenGenerator implements AuthorizationContextTokenGenerator { private boolean enableSigning = true; - private static Map privateKeys = new ConcurrentHashMap(); - private static Map publicCerts = new ConcurrentHashMap(); - private ClaimCache claimsLocalCache; public JWTTokenGenerator() { @@ -319,7 +311,8 @@ protected SignedJWT signJWTWithRSA(SignedJWT signedJWT, JWSAlgorithm jwsAlgorith int tenantId) throws IdentityOAuth2Exception { try { - Key privateKey = getPrivateKey(tenantDomain, tenantId); + Key privateKey = IdentityKeyStoreResolver.getInstance() + .getPrivateKey(tenantDomain, IdentityKeyStoreResolverConstants.InboundProtocol.OAUTH); JWSSigner signer = OAuth2Util.createJWSSigner((RSAPrivateKey) privateKey); signedJWT.sign(signer); return signedJWT; @@ -407,8 +400,8 @@ private long getTTL() { private String getThumbPrint(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { try { - - Certificate certificate = getCertificate(tenantDomain, tenantId); + Certificate certificate = IdentityKeyStoreResolver.getInstance() + .getCertificate(tenantDomain, IdentityKeyStoreResolverConstants.InboundProtocol.OAUTH); // TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization @@ -429,94 +422,6 @@ private String getThumbPrint(String tenantDomain, int tenantId) throws IdentityO } } - private Key getPrivateKey(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { - - if (tenantDomain == null) { - tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; - } - - if (tenantId == 0) { - tenantId = OAuth2Util.getTenantId(tenantDomain); - } - - Key privateKey = null; - - if (!(privateKeys.containsKey(tenantId))) { - - try { - IdentityTenantUtil.initializeRegistry(tenantId, tenantDomain); - } catch (IdentityException e) { - throw new IdentityOAuth2Exception("Error occurred while loading registry for tenant " + tenantDomain, - e); - } - - // get tenant's key store manager - KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); - - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - // derive key store name - String fileName = KeystoreUtils.getKeyStoreFileLocation(tenantDomain); - // obtain private key - privateKey = tenantKSM.getPrivateKey(fileName, tenantDomain); - - } else { - try { - privateKey = tenantKSM.getDefaultPrivateKey(); - } catch (Exception e) { - log.error("Error while obtaining private key for super tenant", e); - } - } - if (privateKey != null) { - privateKeys.put(tenantId, privateKey); - } - } else { - privateKey = privateKeys.get(tenantId); - } - return privateKey; - } - - private Certificate getCertificate(String tenantDomain, int tenantId) throws Exception { - - if (tenantDomain == null) { - tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; - } - - if (tenantId == 0) { - tenantId = OAuth2Util.getTenantId(tenantDomain); - } - - Certificate publicCert = null; - - if (!(publicCerts.containsKey(tenantId))) { - - try { - IdentityTenantUtil.initializeRegistry(tenantId, tenantDomain); - } catch (IdentityException e) { - throw new IdentityOAuth2Exception("Error occurred while loading registry for tenant " + tenantDomain, - e); - } - - // get tenant's key store manager - KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); - - KeyStore keyStore = null; - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - // derive key store name - String fileName = KeystoreUtils.getKeyStoreFileLocation(tenantDomain); - keyStore = tenantKSM.getKeyStore(fileName); - publicCert = keyStore.getCertificate(tenantDomain); - } else { - publicCert = tenantKSM.getDefaultPrimaryCertificate(); - } - if (publicCert != null) { - publicCerts.put(tenantId, publicCert); - } - } else { - publicCert = publicCerts.get(tenantId); - } - return publicCert; - } - /** * Helper method to hexify a byte array. * TODO:need to verify the logic diff --git a/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/JWTTokenIssuer.java b/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/JWTTokenIssuer.java index 6a80d030efb..c7ac52fedb6 100644 --- a/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/JWTTokenIssuer.java +++ b/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/JWTTokenIssuer.java @@ -38,7 +38,6 @@ import org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.base.IdentityConstants; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.common.OAuthConstants; import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException; @@ -459,17 +458,16 @@ protected String signJWTWithRSA(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageC try { String tenantDomain = resolveSigningTenantDomain(tokenContext, authorizationContext); - int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); // Add claim with signer tenant to jwt claims set. jwtClaimsSet = setSignerRealm(tenantDomain, jwtClaimsSet); - Key privateKey = getPrivateKey(tenantDomain, tenantId); + Key privateKey = getPrivateKey(tenantDomain); JWSSigner signer = OAuth2Util.createJWSSigner((RSAPrivateKey) privateKey); JWSHeader.Builder headerBuilder = new JWSHeader.Builder((JWSAlgorithm) signatureAlgorithm); - Certificate certificate = OAuth2Util.getCertificate(tenantDomain, tenantId); + Certificate certificate = OAuth2Util.getCertificate(tenantDomain); String certThumbPrint = OAuth2Util.getThumbPrintWithPrevAlgorithm(certificate, false); - headerBuilder.keyID(OAuth2Util.getKID(OAuth2Util.getCertificate(tenantDomain, tenantId), + headerBuilder.keyID(OAuth2Util.getKID(OAuth2Util.getCertificate(tenantDomain), (JWSAlgorithm) signatureAlgorithm, tenantDomain)); if (authorizationContext != null && authorizationContext.isSubjectTokenFlow()) { diff --git a/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/JWTUtils.java b/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/JWTUtils.java index af002c3fdc3..627c1de8e23 100644 --- a/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/JWTUtils.java +++ b/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/JWTUtils.java @@ -468,8 +468,12 @@ public static X509Certificate resolveSignerCertificate(IdentityProvider idp) thr X509Certificate x509Certificate; String tenantDomain = getTenantDomain(); try { - x509Certificate = (X509Certificate) IdentityApplicationManagementUtil - .decodeCertificate(idp.getCertificate()); + if (IdentityApplicationConstants.RESIDENT_IDP_RESERVED_NAME.equals(idp.getIdentityProviderName())) { + x509Certificate = (X509Certificate) OAuth2Util.getCertificate(tenantDomain); + } else { + x509Certificate = (X509Certificate) IdentityApplicationManagementUtil + .decodeCertificate(idp.getCertificate()); + } } catch (CertificateException e) { throw new IdentityOAuth2Exception("Error occurred while decoding public certificate of Identity Provider " + idp.getIdentityProviderName() + " for tenant domain " + tenantDomain, e); diff --git a/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/OAuth2Util.java b/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/OAuth2Util.java index 52e1855fdb5..b6f6e1bc569 100644 --- a/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/OAuth2Util.java +++ b/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/OAuth2Util.java @@ -64,7 +64,6 @@ import org.json.JSONException; import org.json.JSONObject; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException; import org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; @@ -85,11 +84,14 @@ import org.wso2.carbon.identity.central.log.mgt.utils.LogConstants; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import org.wso2.carbon.identity.consent.server.configs.mgt.exceptions.ConsentServerConfigsMgtException; +import org.wso2.carbon.identity.core.IdentityKeyStoreResolver; import org.wso2.carbon.identity.core.ServiceURLBuilder; import org.wso2.carbon.identity.core.URLBuilderException; import org.wso2.carbon.identity.core.util.IdentityConfigParser; import org.wso2.carbon.identity.core.util.IdentityCoreConstants; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; +import org.wso2.carbon.identity.core.util.IdentityKeyStoreResolverConstants; +import org.wso2.carbon.identity.core.util.IdentityKeyStoreResolverException; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException; @@ -160,7 +162,6 @@ import org.wso2.carbon.utils.DiagnosticLog; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.carbon.utils.security.KeystoreUtils; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -169,8 +170,6 @@ import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.Key; -import java.security.KeyStore; -import java.security.KeyStoreException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; @@ -193,7 +192,6 @@ import java.util.Optional; import java.util.Set; import java.util.TreeMap; -import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -350,9 +348,6 @@ public class OAuth2Util { // System flag to allow the weak keys (key length less than 2048) to be used for the signing. private static final String ALLOW_WEAK_RSA_SIGNER_KEY = "allow_weak_rsa_signer_key"; - private static Map publicCerts = new ConcurrentHashMap(); - private static Map privateKeys = new ConcurrentHashMap(); - // Supported Signature Algorithms private static final String NONE = "NONE"; private static final String SHA256_WITH_RSA = "SHA256withRSA"; @@ -2834,16 +2829,8 @@ public static boolean validateIdToken(String idToken) { return false; } int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); - RSAPublicKey publicKey; - KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId); - - if (!tenantDomain.equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - String fileName = KeystoreUtils.getKeyStoreFileLocation(tenantDomain); - publicKey = (RSAPublicKey) keyStoreManager.getKeyStore(fileName).getCertificate(tenantDomain) - .getPublicKey(); - } else { - publicKey = (RSAPublicKey) keyStoreManager.getDefaultPublicKey(); - } + RSAPublicKey publicKey = IdentityKeyStoreResolver.getInstance() + .getPublicKey(tenantDomain, IdentityKeyStoreResolverConstants.InboundProtocol.OAUTH); SignedJWT signedJWT = SignedJWT.parse(idToken); JWSVerifier verifier = new RSASSAVerifier(publicKey); @@ -3359,42 +3346,34 @@ public static JWT signJWTWithRSA(JWTClaimsSet jwtClaimsSet, JWSAlgorithm signatu } } - public static Key getPrivateKey(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { - - Key privateKey; - if (!(privateKeys.containsKey(tenantId))) { - - try { - IdentityTenantUtil.initializeRegistry(tenantId, tenantDomain); - } catch (IdentityException e) { - throw new IdentityOAuth2Exception("Error occurred while loading registry for tenant " + tenantDomain, - e); - } + /** + * Method to obatin Default Private key for OAuth2 protocol. + * + * @param tenantDomain Tenant Domain as a String. + * @return Default Private key for OAuth2 protocol. + * @throws IdentityOAuth2Exception When failed to obtain the private key for the requested tenant. + */ + public static Key getPrivateKey(String tenantDomain) throws IdentityOAuth2Exception { - // get tenant's key store manager - KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); + try { + return IdentityKeyStoreResolver.getInstance().getPrivateKey( + tenantDomain, IdentityKeyStoreResolverConstants.InboundProtocol.OAUTH); + } catch (IdentityKeyStoreResolverException e) { + throw new IdentityOAuth2Exception("Error while obtaining private key", e); + } + } - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - // derive key store name - String fileName = KeystoreUtils.getKeyStoreFileLocation(tenantDomain); - // obtain private key - privateKey = tenantKSM.getPrivateKey(fileName, tenantDomain); + /** + * Method to obatin Default Private key for OAuth2 protocol. + * + * @param tenantDomain Tenant Domain as a String. + * @param tenantId Tenan ID as an integer. + * @return Default Private key for OAuth2 protocol. + * @throws IdentityOAuth2Exception When failed to obtain the private key for the requested tenant. + */ + public static Key getPrivateKey(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { - } else { - try { - privateKey = tenantKSM.getDefaultPrivateKey(); - } catch (Exception e) { - throw new IdentityOAuth2Exception("Error while obtaining private key for super tenant", e); - } - } - //privateKey will not be null always - privateKeys.put(tenantId, privateKey); - } else { - //privateKey will not be null because containsKey() true says given key is exist and ConcurrentHashMap - // does not allow to store null values - privateKey = privateKeys.get(tenantId); - } - return privateKey; + return getPrivateKey(tenantDomain); } /** @@ -3546,62 +3525,30 @@ private static boolean isRSAAlgorithm(JWEAlgorithm algorithm) { * Method to obatin Default Signing certificate for the tenant. * * @param tenantDomain Tenant Domain as a String. - * @param tenantId Tenan ID as an integer. - * @return Default Signing Certificate of the tenant domain. + * @return Default Signing Certificate of the tenant domain for the OAuth2 protocol. * @throws IdentityOAuth2Exception When failed to obtain the certificate for the requested tenant. */ - public static Certificate getCertificate(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { - - Certificate publicCert = null; - - if (!(publicCerts.containsKey(tenantId))) { - if (log.isDebugEnabled()) { - log.debug(String.format("Obtaining certificate for the tenant %s", tenantDomain)); - } - try { - IdentityTenantUtil.initializeRegistry(tenantId, tenantDomain); - } catch (IdentityException e) { - throw new IdentityOAuth2Exception("Error occurred while loading registry for tenant " + tenantDomain, - e); - } + public static Certificate getCertificate(String tenantDomain) throws IdentityOAuth2Exception { - // get tenant's key store manager - KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); + try { + return IdentityKeyStoreResolver.getInstance().getCertificate( + tenantDomain, IdentityKeyStoreResolverConstants.InboundProtocol.OAUTH); + } catch (IdentityKeyStoreResolverException e) { + throw new IdentityOAuth2Exception("Error while obtaining public certificate.", e); + } + } - KeyStore keyStore = null; - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - // derive key store name - String fileName = KeystoreUtils.getKeyStoreFileLocation(tenantDomain); - if (log.isDebugEnabled()) { - log.debug(String.format("Loading default tenant certificate for tenant : %s from the KeyStore" + - " %s", tenantDomain, fileName)); - } - try { - keyStore = tenantKSM.getKeyStore(fileName); - publicCert = keyStore.getCertificate(tenantDomain); - } catch (KeyStoreException e) { - throw new IdentityOAuth2Exception("Error occurred while loading public certificate for tenant: " + - tenantDomain, e); - } catch (Exception e) { - throw new IdentityOAuth2Exception("Error occurred while loading Keystore for tenant: " + - tenantDomain, e); - } + /** + * Method to obatin Default Signing certificate for the tenant. + * + * @param tenantDomain Tenant Domain as a String. + * @param tenantId Tenan ID as an integer. + * @return Default Signing Certificate of the tenant domain for the OAuth2 protocol. + * @throws IdentityOAuth2Exception When failed to obtain the certificate for the requested tenant. + */ + public static Certificate getCertificate(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { - } else { - try { - publicCert = tenantKSM.getDefaultPrimaryCertificate(); - } catch (Exception e) { - throw new IdentityOAuth2Exception("Error occurred while loading default public " + - "certificate for tenant: " + tenantDomain, e); - } - } - if (publicCert != null) { - publicCerts.put(tenantId, publicCert); - } - } else { - publicCert = publicCerts.get(tenantId); - } - return publicCert; + return getCertificate(tenantDomain); } /** diff --git a/components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth2/authcontext/JWTTokenGeneratorTest.java b/components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth2/authcontext/JWTTokenGeneratorTest.java index 2ab225994c8..26629058e49 100644 --- a/components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth2/authcontext/JWTTokenGeneratorTest.java +++ b/components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth2/authcontext/JWTTokenGeneratorTest.java @@ -33,6 +33,7 @@ import org.wso2.carbon.identity.common.testng.WithH2Database; import org.wso2.carbon.identity.common.testng.WithKeyStore; import org.wso2.carbon.identity.common.testng.WithRealmService; +import org.wso2.carbon.identity.core.IdentityKeyStoreResolver; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException; @@ -46,7 +47,6 @@ import org.wso2.carbon.identity.oauth2.internal.OAuth2ServiceComponentHolder; import org.wso2.carbon.identity.oauth2.keyidprovider.DefaultKeyIDProviderImpl; import org.wso2.carbon.identity.oauth2.model.AccessTokenDO; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; import org.wso2.carbon.identity.oauth2.validators.OAuth2TokenValidationMessageContext; import org.wso2.carbon.identity.testutil.ReadCertStoreSampleUtil; import org.wso2.carbon.user.core.UserCoreConstants; @@ -163,16 +163,16 @@ public void testGenerateToken() throws Exception { addSampleOauth2Application(); ClaimCache claimsLocalCache = ClaimCache.getInstance(); setPrivateField(jwtTokenGenerator, "claimsLocalCache", claimsLocalCache); - Map publicCerts = new ConcurrentHashMap<>(); - publicCerts.put(-1234, ReadCertStoreSampleUtil.createKeyStore(getClass()) + Map publicCerts = new ConcurrentHashMap<>(); + publicCerts.put("-1234", ReadCertStoreSampleUtil.createKeyStore(getClass()) .getCertificate("wso2carbon")); OAuthComponentServiceHolder.getInstance().setRealmService(realmService); when(realmService.getTenantManager()).thenReturn(tenantManager); - setFinalStatic(OAuth2Util.class.getDeclaredField("publicCerts"), publicCerts); - Map privateKeys = new ConcurrentHashMap<>(); - privateKeys.put(-1234, ReadCertStoreSampleUtil.createKeyStore(getClass()) + setFinalStatic(IdentityKeyStoreResolver.class.getDeclaredField("publicCerts"), publicCerts); + Map privateKeys = new ConcurrentHashMap<>(); + privateKeys.put("-1234", ReadCertStoreSampleUtil.createKeyStore(getClass()) .getKey("wso2carbon", "wso2carbon".toCharArray())); - setFinalStatic(OAuth2Util.class.getDeclaredField("privateKeys"), privateKeys); + setFinalStatic(IdentityKeyStoreResolver.class.getDeclaredField("privateKeys"), privateKeys); accessToken.setTokenType("Bearer"); oAuth2TokenValidationRequestDTO.setAccessToken(accessToken); diff --git a/components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/openidconnect/DefaultIDTokenBuilderTest.java b/components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/openidconnect/DefaultIDTokenBuilderTest.java index 48ca3b418b4..1b9ed2a3153 100644 --- a/components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/openidconnect/DefaultIDTokenBuilderTest.java +++ b/components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/openidconnect/DefaultIDTokenBuilderTest.java @@ -43,6 +43,7 @@ import org.wso2.carbon.identity.common.testng.WithH2Database; import org.wso2.carbon.identity.common.testng.WithKeyStore; import org.wso2.carbon.identity.common.testng.WithRealmService; +import org.wso2.carbon.identity.core.IdentityKeyStoreResolver; import org.wso2.carbon.identity.core.persistence.JDBCPersistenceManager; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; @@ -70,7 +71,6 @@ import org.wso2.carbon.identity.oauth2.test.utils.CommonTestUtils; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; import org.wso2.carbon.identity.oauth2.token.handlers.grant.saml.SAML2BearerGrantHandlerTest; -import org.wso2.carbon.identity.oauth2.util.OAuth2Util; import org.wso2.carbon.identity.openidconnect.dao.ScopeClaimMappingDAOImpl; import org.wso2.carbon.identity.openidconnect.internal.OpenIDConnectServiceComponentHolder; import org.wso2.carbon.identity.openidconnect.model.RequestedClaim; @@ -250,14 +250,14 @@ public void setUp() throws Exception { .addUser(TestConstants.USER_NAME, TestConstants.PASSWORD, new String[0], claims, TestConstants.DEFAULT_PROFILE); - Map publicCerts = new ConcurrentHashMap<>(); - publicCerts.put(SUPER_TENANT_ID, ReadCertStoreSampleUtil.createKeyStore(getClass()) + Map publicCerts = new ConcurrentHashMap<>(); + publicCerts.put(String.valueOf(SUPER_TENANT_ID), ReadCertStoreSampleUtil.createKeyStore(getClass()) .getCertificate("wso2carbon")); - setFinalStatic(OAuth2Util.class.getDeclaredField("publicCerts"), publicCerts); - Map privateKeys = new ConcurrentHashMap<>(); - privateKeys.put(SUPER_TENANT_ID, ReadCertStoreSampleUtil.createKeyStore(getClass()) + setFinalStatic(IdentityKeyStoreResolver.class.getDeclaredField("publicCerts"), publicCerts); + Map privateKeys = new ConcurrentHashMap<>(); + privateKeys.put(String.valueOf(SUPER_TENANT_ID), ReadCertStoreSampleUtil.createKeyStore(getClass()) .getKey("wso2carbon", "wso2carbon".toCharArray())); - setFinalStatic(OAuth2Util.class.getDeclaredField("privateKeys"), privateKeys); + setFinalStatic(IdentityKeyStoreResolver.class.getDeclaredField("privateKeys"), privateKeys); OpenIDConnectServiceComponentHolder.getInstance() .getOpenIDConnectClaimFilters().add(new OpenIDConnectClaimFilterImpl());