33using System ;
44using System . Collections . Concurrent ;
55using System . Collections . Generic ;
6+ using System . Linq ;
67using System . Net . Http ;
78using System . Security . Cryptography ;
89using System . Text ;
@@ -100,14 +101,14 @@ private string GetJwtToken()
100101
101102 private string CreateJwtToken ( )
102103 {
103- var header = JsonHelper . Serialize ( new { alg = "ES256" , kid = settings . P8PrivateKeyId } ) ;
104+ var header = JsonHelper . Serialize ( new { alg = "ES256" , kid = CleanP8Key ( settings . P8PrivateKeyId ) } ) ;
104105 var payload = JsonHelper . Serialize ( new { iss = settings . TeamId , iat = ToEpoch ( DateTime . UtcNow ) } ) ;
105106 var headerBase64 = Convert . ToBase64String ( Encoding . UTF8 . GetBytes ( header ) ) ;
106107 var payloadBasae64 = Convert . ToBase64String ( Encoding . UTF8 . GetBytes ( payload ) ) ;
107108 var unsignedJwtData = $ "{ headerBase64 } .{ payloadBasae64 } ";
108109 var unsignedJwtBytes = Encoding . UTF8 . GetBytes ( unsignedJwtData ) ;
109110 using var dsa = ECDsa . Create ( ) ;
110- dsa . ImportPkcs8PrivateKey ( Convert . FromBase64String ( settings . P8PrivateKey ) , out _ ) ;
111+ dsa . ImportPkcs8PrivateKey ( Convert . FromBase64String ( CleanP8Key ( settings . P8PrivateKey ) ) , out _ ) ;
111112 var signature = dsa . SignData ( unsignedJwtBytes , 0 , unsignedJwtBytes . Length , HashAlgorithmName . SHA256 ) ;
112113 return $ "{ unsignedJwtData } .{ Convert . ToBase64String ( signature ) } ";
113114 }
@@ -117,5 +118,28 @@ private static int ToEpoch(DateTime time)
117118 var span = DateTime . UtcNow - new DateTime ( 1970 , 1 , 1 ) ;
118119 return Convert . ToInt32 ( span . TotalSeconds ) ;
119120 }
121+
122+ private static string CleanP8Key ( string p8Key )
123+ {
124+ // If we have an empty p8Key, then don't bother doing any tasks.
125+ if ( string . IsNullOrEmpty ( p8Key ) )
126+ {
127+ return p8Key ;
128+ }
129+
130+ List < string > lines = p8Key . Split ( new char [ ] { '\n ' } ) . ToList ( ) ;
131+ if ( 0 != lines . Count && lines [ 0 ] . StartsWith ( "-----BEGIN PRIVATE KEY-----" ) )
132+ {
133+ lines . RemoveAt ( 0 ) ;
134+ }
135+
136+ if ( 0 != lines . Count && lines [ lines . Count - 1 ] . StartsWith ( "-----END PRIVATE KEY-----" ) )
137+ {
138+ lines . RemoveAt ( lines . Count - 1 ) ;
139+ }
140+
141+ string result = string . Join ( "" , lines ) ;
142+ return result ;
143+ }
120144 }
121145}
0 commit comments