33using Google . Apis . Auth . OAuth2 ;
44using Google . Apis . CertificateManager . v1 ;
55using Google . Apis . Services ;
6+ using Google . Apis . Iam . v1 ;
7+ using Google . Apis . Iam . v1 . Data ;
8+ using System . Text ;
9+ using System ;
10+
11+ using Keyfactor . Logging ;
12+ using Microsoft . Extensions . Logging ;
13+
614
715namespace Keyfactor . Extensions . Orchestrator . GcpCertManager . Client
816{
917 public class GcpCertificateManagerClient
1018 {
1119 public CertificateManagerService GetGoogleCredentials ( string credentialFileName )
1220 {
21+ ILogger _logger = LogHandler . GetClassLogger < CertificateManagerService > ( ) ;
22+
1323 //Credentials file needs to be in the same location of the executing assembly
14- var strExeFilePath = Assembly . GetExecutingAssembly ( ) . Location ;
15- var strWorkPath = Path . GetDirectoryName ( strExeFilePath ) ;
16- var strSettingsJsonFilePath = Path . Combine ( strWorkPath ?? string . Empty , credentialFileName ) ;
24+ GoogleCredential credentials ;
1725
18- var stream = new FileStream ( strSettingsJsonFilePath ,
19- FileMode . Open
20- ) ;
26+ if ( ! string . IsNullOrEmpty ( credentialFileName ) )
27+ {
28+ _logger . LogDebug ( "Has credential file name" ) ;
29+ var strExeFilePath = Assembly . GetExecutingAssembly ( ) . Location ;
30+ var strWorkPath = Path . GetDirectoryName ( strExeFilePath ) ;
31+ var strSettingsJsonFilePath = Path . Combine ( strWorkPath ?? string . Empty , credentialFileName ) ;
2132
22- var credentials = GoogleCredential . FromStream ( stream ) ;
33+ var stream = new FileStream ( strSettingsJsonFilePath ,
34+ FileMode . Open
35+ ) ;
36+
37+ credentials = GoogleCredential . FromStream ( stream ) ;
38+ }
39+ else
40+ {
41+ _logger . LogDebug ( "No credential file name" ) ;
42+ credentials = GoogleCredential . GetApplicationDefaultAsync ( ) . Result ;
43+ }
2344
2445 var service = new CertificateManagerService ( new BaseClientService . Initializer
2546 {
@@ -28,5 +49,21 @@ public CertificateManagerService GetGoogleCredentials(string credentialFileName)
2849
2950 return service ;
3051 }
52+
53+ public ServiceAccountKey CreateServiceAccountKey ( string serviceAccountEmail )
54+ {
55+ GoogleCredential credential = GoogleCredential . GetApplicationDefault ( ) . CreateScoped ( IamService . Scope . CloudPlatform ) ;
56+ IamService service = new IamService ( new IamService . Initializer
57+ {
58+ HttpClientInitializer = credential
59+ } ) ;
60+
61+ var key = service . Projects . ServiceAccounts . Keys . Create ( new CreateServiceAccountKeyRequest ( ) , "projects/-/serviceAccounts/" + serviceAccountEmail ) . Execute ( ) ;
62+
63+ byte [ ] valueBytes = System . Convert . FromBase64String ( key . PrivateKeyData ) ;
64+ string jsonKeyContent = Encoding . UTF8 . GetString ( valueBytes ) ;
65+
66+ return key ;
67+ }
3168 }
3269}
0 commit comments