Pushsharp support of Apple Push Notification Authentication Key - c#

Does pushsharp supports a new Apple approach for sending APN using Apple Push Notification Authentication Key (which never expires) instead of using Certificates? Is any way to use it with pushsharp? If not, is there any other C# library to support it?

here you are:
private string GetToken()
{
var algorithm = "ES256";
var teamID = "teamID";
var apnsKeyID = "apnsKeyID";
var apnsAuthKeyPath = #"apnsAuthKeyPath";
var epochNow = DateTimeOffset.Now.ToUnixTimeSeconds();
var header = new Dictionary<string, object>()
{
{ "alg", algorithm },
{ "kid" , apnsKeyID }
};
var payload = new Dictionary<string, object>()
{
{ "iss", teamID },
{ "iat", epochNow }
};
var privateKey = GetPrivateKey(apnsAuthKeyPath);
var token = Jose.JWT.Encode(payload, privateKey, algorithm: Jose.JwsAlgorithm.ES256, extraHeaders: header);
return token;
}
private CngKey GetPrivateKey(string apnsAuthKey)
{
using (var reader = File.OpenText(apnsAuthKey))
{
var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded();
var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded();
var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
return EccKey.New(x, y, d);
}
}
then you can simply call send method in apns.

Related

Fetching secretvalue from CDK not working

I have stored an api key to invoke APigateway in secret manager. And I am trying to fetch that secret from cdk and attach to the rule's header parameter as given below
var secret = Amazon.CDK.AWS.SecretsManager.Secret.FromSecretAttributes(this, "SCMId", new Amazon.CDK.AWS.SecretsManager.SecretAttributes
{
SecretCompleteArn = apikeyArn
});
var apikey = secret.SecretValueFromJson("ApiKey").Resolve;
var httpParameters = new Amazon.CDK.AWS.Events.CfnRule.HttpParametersProperty { HeaderParameters = new Dictionary<string, string> { { "x-api-key", apikey.ToString() } } };
Then the event target with above http parameter
var eventRule = new Amazon.CDK.AWS.Events.CfnRule(this, ruleId, new Amazon.CDK.AWS.Events.CfnRuleProps
{
EventBusName = busName,
Name = ruleName,
Description = description,
EventPattern = eventPattern,
Targets = new[]
{
new Amazon.CDK.AWS.Events.CfnRule.TargetProperty
{
Id = id,
Arn = apiArn,
HttpParameters = httpParameters,
RoleArn = roleArn,
}
}
});
Still the api key is not working and I am getting 403 error when that particular event trying to invoke api.

Using ES256 algorithm with jwt-dotnet for Apple AppStore

I'm trying to generate a jwt token to connect to AppStore API. I'm using the jwt-dotnet library to do this.
Apple requires ES256 to be used and the jwt-dotnet is asking for a public key to do the job. I only downloaded a private key from AppStore. How do I handle this?
Here's my code:
public static string GenerateAppStoreJwtToken()
{
var header = new Dictionary<string, object>()
{
{ "kid", "MY_VALUE" },
{ "typ", "JWT" }
};
var scope = new string[1] { "GET /v1/apps?filter[platform]=IOS" };
var payload = new Dictionary<string, object>
{
{ "iss", "MY_VALUE" },
{ "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
{ "exp", DateTimeOffset.UtcNow.AddMinutes(20).ToUnixTimeSeconds() },
{ "aud", "appstoreconnect-v1" },
{ "scope", scope }
};
IJwtAlgorithm algorithm = new ES256Algorithm(???); // What am I going to use here?
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(header, payload, privateKey);
return token;
}
For anyone, like me, who usew JWT-dotnet elsewhere so doesn't want to use a different JWT package, this worked:
Converted the apple private key by removing the header and footer ("-----BEGIN PRIVATE KEY-----" etc) and removing the end of line characters to make a single string for easier storage.
Convert from Base64 and store in a ReadOnlySpan
ReadOnlySpan<byte> keyAsSpan = Convert.FromBase64String(key);
var prvKey = ECDsa.Create();
prvKey.ImportPkcs8PrivateKey(keyAsSpan,out var read);
Create the algorithm. A blank ECDsa instance is needed to prevent an NullException but it is not needed just for signing the token, only verifying which isn't necessary.
IJwtAlgorithm algorithm = new ES256Algorithm(ECDsa.Create(), prvKey)
I was able to receive a reply token from apple using this method.
Here's the final solution that worked for me. I ended up switching to jose-jwt but I'm pretty sure you can handle the same thing with jwt-dotnet. I just found working with jose-jwt a bit easier. Here's the link to jose-jwt: https://github.com/dvsekhvalnov/jose-jwt
And here's the final code. Please note that I did indeed use the private key I find in the p8 file and didn't have to convert anything. So the privateKey parameter I'm passing to the GenerateAppStoreJwtToken() function comes directly from the p8 file.
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using Jose;
public static string GenerateAppStoreJwtToken(string privateKey)
{
var header = new Dictionary<string, object>()
{
{ "alg", "ES256" },
{ "kid", "MY_VALUE" },
{ "typ", "JWT" }
};
var scope = new string[1] { "GET /v1/apps?filter[platform]=IOS" };
var payload = new Dictionary<string, object>
{
{ "iss", "MY_VALUE" },
{ "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
{ "exp", DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds() },
{ "aud", "appstoreconnect-v1" },
{ "scope", scope }
};
CngKey key = CngKey.Import(Convert.FromBase64String(privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob);
string token = JWT.Encode(payload, key, JwsAlgorithm.ES256, header);
return token;
}

AndroidPublisherService - Play Developer API Client - Upload aab failes due to bad credentials

Trying to make use of the AndroidPublisherService from Play Developer API Client.
I can list active tracks and the releases in those tracks, but when I try to upload a new build there seems to be no way of attaching the authentication already made previously to read data.
I've authenticated using var googleCredentials = GoogleCredential.FromStream(keyDataStream) .CreateWithUser(serviceUsername); where serviceUsername is the email for my service account.
private static void Execute(string packageName, string aabfile, string credfile, string serviceUsername)
{
var credentialsFilename = credfile;
if (string.IsNullOrWhiteSpace(credentialsFilename))
{
// Check env. var
credentialsFilename =
Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",
EnvironmentVariableTarget.Process);
}
Console.WriteLine($"Using credentials {credfile} with package {packageName} for aab file {aabfile}");
var keyDataStream = File.OpenRead(credentialsFilename);
var googleCredentials = GoogleCredential.FromStream(keyDataStream)
.CreateWithUser(serviceUsername);
var credentials = googleCredentials.UnderlyingCredential as ServiceAccountCredential;
var service = new AndroidPublisherService();
var edit = service.Edits.Insert(new AppEdit { ExpiryTimeSeconds = "3600" }, packageName);
edit.Credential = credentials;
var activeEditSession = edit.Execute();
Console.WriteLine($"Edits started with id {activeEditSession.Id}");
var tracksList = service.Edits.Tracks.List(packageName, activeEditSession.Id);
tracksList.Credential = credentials;
var tracksResponse = tracksList.Execute();
foreach (var track in tracksResponse.Tracks)
{
Console.WriteLine($"Track: {track.TrackValue}");
Console.WriteLine("Releases: ");
foreach (var rel in track.Releases)
Console.WriteLine($"{rel.Name} version: {rel.VersionCodes.FirstOrDefault()} - Status: {rel.Status}");
}
using var fileStream = File.OpenRead(aabfile);
var upload = service.Edits.Bundles.Upload(packageName, activeEditSession.Id, fileStream, "application/octet-stream");
var uploadProgress = upload.Upload();
if (uploadProgress == null || uploadProgress.Exception != null)
{
Console.WriteLine($"Failed to upload. Error: {uploadProgress?.Exception}");
return;
}
Console.WriteLine($"Upload {uploadProgress.Status}");
var tracksUpdate = service.Edits.Tracks.Update(new Track
{
Releases = new List<TrackRelease>(new[]
{
new TrackRelease
{
Name = "Roswell - Grenis Dev Test",
Status = "completed",
VersionCodes = new List<long?>(new[] {(long?) upload?.ResponseBody?.VersionCode})
}
})
}, packageName, activeEditSession.Id, "internal");
tracksUpdate.Credential = credentials;
var trackResult = tracksUpdate.Execute();
Console.WriteLine($"Track {trackResult?.TrackValue}");
var commitResult = service.Edits.Commit(packageName, activeEditSession.Id);
Console.WriteLine($"{commitResult.EditId} has been committed");
}
And as the code points out, all action objects such as tracksList.Credential = credentials; can be given the credentials generated from the service account.
BUT the actual upload action var upload = service.Edits.Bundles.Upload(packageName, activeEditSession.Id, fileStream, "application/octet-stream"); does not expose a .Credential object, and it always fails with:
The service androidpublisher has thrown an exception: Google.GoogleApiException: Google.Apis.Requests.RequestError
Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. [401]
Errors [
Message[Login Required.] Location[Authorization - header] Reason[required] Domain[global]
]
at Google.Apis.Upload.ResumableUpload`1.InitiateSessionAsync(CancellationToken cancellationToken)
at Google.Apis.Upload.ResumableUpload.UploadAsync(CancellationToken cancellationToken)
So, how would I go about providing the actual Upload action with the given credentials here?
Managed to figure this out during the day, I was missing one call to CreateScoped() when creating the GoogleCredential object as well as a call to InitiateSession() on the upload object.
var googleCredentials = GoogleCredential.FromStream(keyDataStream)
.CreateWithUser(serviceUsername)
.CreateScoped(AndroidPublisherService.Scope.Androidpublisher);
Once that was done I could then get a valid oauth token by calling
var googleCredentials = GoogleCredential.FromStream(keyDataStream)
.CreateWithUser(serviceUsername)
.CreateScoped(AndroidPublisherService.Scope.Androidpublisher);
var credentials = googleCredentials.UnderlyingCredential as ServiceAccountCredential;
var oauthToken = credentials?.GetAccessTokenForRequestAsync(AndroidPublisherService.Scope.Androidpublisher).Result;
And I can now use that oauth token in the upload request:
upload.OauthToken = oauthToken;
_ = await upload.InitiateSessionAsync();
var uploadProgress = await upload.UploadAsync();
if (uploadProgress == null || uploadProgress.Exception != null)
{
Console.WriteLine($"Failed to upload. Error: {uploadProgress?.Exception}");
return;
}
The full code example for successfully uploading a new aab file to google play store internal test track thus looks something like this:
private async Task UploadGooglePlayRelease(string fileToUpload, string changeLogFile, string serviceUsername, string packageName)
{
var serviceAccountFile = ResolveServiceAccountCertificateInfoFile();
if (!serviceAccountFile.Exists)
throw new ApplicationException($"Failed to find the service account certificate file. {serviceAccountFile.FullName}");
var keyDataStream = File.OpenRead(serviceAccountFile.FullName);
var googleCredentials = GoogleCredential.FromStream(keyDataStream)
.CreateWithUser(serviceUsername)
.CreateScoped(AndroidPublisherService.Scope.Androidpublisher);
var credentials = googleCredentials.UnderlyingCredential as ServiceAccountCredential;
var oauthToken = credentials?.GetAccessTokenForRequestAsync(AndroidPublisherService.Scope.Androidpublisher).Result;
var service = new AndroidPublisherService();
var edit = service.Edits.Insert(new AppEdit { ExpiryTimeSeconds = "3600" }, packageName);
edit.Credential = credentials;
var activeEditSession = await edit.ExecuteAsync();
_logger.LogInformation($"Edits started with id {activeEditSession.Id}");
var tracksList = service.Edits.Tracks.List(packageName, activeEditSession.Id);
tracksList.Credential = credentials;
var tracksResponse = await tracksList.ExecuteAsync();
foreach (var track in tracksResponse.Tracks)
{
_logger.LogInformation($"Track: {track.TrackValue}");
_logger.LogInformation("Releases: ");
foreach (var rel in track.Releases)
_logger.LogInformation($"{rel.Name} version: {rel.VersionCodes.FirstOrDefault()} - Status: {rel.Status}");
}
var fileStream = File.OpenRead(fileToUpload);
var upload = service.Edits.Bundles.Upload(packageName, activeEditSession.Id, fileStream, "application/octet-stream");
upload.OauthToken = oauthToken;
_ = await upload.InitiateSessionAsync();
var uploadProgress = await upload.UploadAsync();
if (uploadProgress == null || uploadProgress.Exception != null)
{
Console.WriteLine($"Failed to upload. Error: {uploadProgress?.Exception}");
return;
}
_logger.LogInformation($"Upload {uploadProgress.Status}");
var releaseNotes = await File.ReadAllTextAsync(changeLogFile);
var tracksUpdate = service.Edits.Tracks.Update(new Track
{
Releases = new List<TrackRelease>(new[]
{
new TrackRelease
{
Name = $"{upload?.ResponseBody?.VersionCode}",
Status = "completed",
InAppUpdatePriority = 5,
CountryTargeting = new CountryTargeting { IncludeRestOfWorld = true },
ReleaseNotes = new List<LocalizedText>(new []{ new LocalizedText { Language = "en-US", Text = releaseNotes } }),
VersionCodes = new List<long?>(new[] {(long?) upload?.ResponseBody?.VersionCode})
}
})
}, packageName, activeEditSession.Id, "internal");
tracksUpdate.Credential = credentials;
var trackResult = await tracksUpdate.ExecuteAsync();
_logger.LogInformation($"Track {trackResult?.TrackValue}");
var commitResult = service.Edits.Commit(packageName, activeEditSession.Id);
commitResult.Credential = credentials;
await commitResult.ExecuteAsync();
_logger.LogInformation($"{commitResult.EditId} has been committed");
}

Net Core JWT Signing Credentials

I am following this tutorial:
https://jonhilton.net/2017/10/11/secure-your-asp.net-core-2.0-api-part-1---issuing-a-jwt/
Here is the main code:
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "yourdomain.com",
audience: "yourdomain.com",
claims: user.Claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
The part I don't understand is where it looks for a key in the configuration file, but it gives no indicator what this key is/should be?
One option is to keep a repository of symmetric signing keys that are associated with the "kid" claim in the JWT header. For example, keep a file of keys in an encrypted AWS S3 bucket. The .NET Core 2 web service pulls the file of keys from the S3 bucket every X minutes.
When a request arrives, the "kid" claim value is used to look up the associated symmetric key from a collection that was built from the pulled file.
EXAMPLE:
Configure an IssuerSigningKeyResolver function.
public static IServiceCollection AddJwtValidation(this IServiceCollection services)
{
IServiceProvider sp = services.BuildServiceProvider();
ConfigRoot = sp.GetRequiredService<IConfigurationRoot>();
tokenAudience = ConfigRoot["JwtToken:Audience"];
tokenIssuer = ConfigRoot["JwtToken:Issuer"];
SecurityKeyManager.Start();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Audience = tokenAudience;
options.ClaimsIssuer = tokenIssuer;
options.TokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
RequireSignedTokens = true,
IssuerSigningKeyResolver = MyIssuerSigningKeyResolver,
....
The IssuerSigningKeyResolver is defined as:
public static List<SecurityKey> MyIssuerSigningKeyResolver(string token, SecurityToken jwtToken, string kid, TokenValidationParameters validationParameters)
{
List<SecurityKey> keys = new List<SecurityKey>();
if (validationParameters == null)
{
throw new ArgumentNullException("validationParameters");
}
if (jwtToken == null)
{
throw new ArgumentNullException("securityToken");
}
if (!string.IsNullOrEmpty(kid))
{
SymmetricSecurityKey key = SecurityKeyManager.GetSecurityKey(kid);
keys.Add(key);
}
return keys;
}
The SecurityKeyManager periodically pulls the key file from AWS S3 and stores the keys in a collection.
// Example approved-clients.txt file in the approved-clients S3 bucket (us-east-1).
// //kid,key,active
// customer1,AAAAAAAAAAAAAAAA,true
// customer2,BBBBBBBBBBBBBBBB,true
// customer3,CCCCCCCCCCCCCCCC,true
// customer4,DDDDDDDDDDDDDDDD,true
namespace My.CoreServices.Security.Jwt
{
public class SecurityKeyManager
{
private const int RELOAD_TIMER_DELAY_SECONDS = 3 * 1000;
private const int RELOAD_TIMER_PERIOD_MINUTES = 60 * 60 * 1000;
[DebuggerDisplay("{Kid} {SymmetricKey} {Active}")]
internal class ApprovedClient
{
public string Kid { get; set; }
public bool Active { get; set; }
public string SymmetricKey { get; set; }
};
private static List<SymmetricSecurityKey> securityKeys = new List<SymmetricSecurityKey>();
private static Timer reloadTimer = null;
private static object keySync = new object();
public static void Start()
{
// Start a new timer to reload all the security keys every RELOAD_TIMER_PERIOD_MINUTES.
if (reloadTimer == null)
{
reloadTimer = new Timer(async (t) =>
{
try
{
List<ApprovedClient> approvedClients = new List<ApprovedClient>();
Log.Debug("Pulling latest approved client symmetric keys for JWT signature validation");
string awsAccessKeyId = JwtConfigure.ConfigRoot["AWS:KeyManagement:AccessKeyId"];
string awsSecretAccessKey = fromBase64(JwtConfigure.ConfigRoot["AWS:KeyManagement:SecretAccessKey"]);
string awsRegion = JwtConfigure.ConfigRoot["AWS:KeyManagement:Region"];
using (var client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.GetBySystemName(awsRegion)))
{
var request = new GetObjectRequest();
request.BucketName = JwtConfigure.ConfigRoot["AWS:KeyManagement:Bucket"];
request.Key = JwtConfigure.ConfigRoot["AWS:KeyManagement:Key"];
var response = await client.GetObjectAsync(request);
using (StreamReader sr = new StreamReader(response.ResponseStream))
{
while (sr.Peek() > 0)
{
string line = await sr.ReadLineAsync();
// Ignore comment lines in the approved-client file
if (!line.StartsWith("//") && !string.IsNullOrEmpty(line))
{
// Each line of the file should only have 3 items:
// kid, key, active
string[] items = line.Split(',');
approvedClients.Add(new ApprovedClient()
{
Kid = items[0],
SymmetricKey = items[1],
Active = Boolean.Parse(items[2])
});
}
}
}
}
lock (keySync)
{
if (approvedClients.Count > 0)
{
// Clear the security key list and repopulate
securityKeys.Clear();
foreach (var approvedClient in approvedClients)
{
if (approvedClient.Active)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(approvedClient.SymmetricKey));
key.KeyId = approvedClient.Kid;
securityKeys.Add(key);
}
}
}
}
Log.Information($"Reloaded security keys");
}
catch (Exception ex)
{
Log.Warning($"Error getting current security keys - {ex.Message}");
}
}, null, RELOAD_TIMER_DELAY_SECONDS, RELOAD_TIMER_PERIOD_MINUTES);
}
}
public static void Stop()
{
if (reloadTimer != null)
{
reloadTimer.Dispose();
reloadTimer = null;
}
}
public static SymmetricSecurityKey GetSecurityKey(string kid)
{
SymmetricSecurityKey securityKey = null;
lock (keySync)
{
byte[] keyData = securityKeys.Where(k => k.KeyId == kid).Select(x => x.Key).FirstOrDefault();
if (keyData != null)
{
securityKey = new SymmetricSecurityKey(keyData);
securityKey.KeyId = kid;
}
}
return securityKey;
}
private static string fromBase64(string encodedValue)
{
byte[] decodedBytes = Convert.FromBase64String(encodedValue);
return Encoding.UTF8.GetString(decodedBytes);
}
}
}
Ensure that when a JWT is created for a specific user/customer/etc, the "kid" claim is set in the JWT header.
{
"alg": "HS256",
"kid": "customer2",
"typ": "JWT"
}
The value of "kid" will be passed as the third parameter to the IssuerSigningKeyResolver method. That kid will then be used to lookup the associated symmetric key that is used to validate the JWT signature.
This key can be any string: it's the secret key used to both encrypt and decrypt your secure payload.
From Wikipedia:
Symmetric-key algorithms are algorithms for cryptography that use the same cryptographic keys for both encryption of plaintext and decryption of ciphertext. The keys, in practice, represent a shared secret between two or more parties that can be used to maintain a private information link.
As for how to generate an efficient key, you can refer to this question on crypto.stackexchange.

Validating Google OpenID Connect JWT ID Token

I'm trying to upgrade my MVC website to use the new OpenID Connect standard. The OWIN middleware seems to be pretty robust, but unfortunately only supports the
"form_post" response type. This means that Google isn't compatible, as it returns all the tokens in a the url after a "#", so they never reach the server and never trigger the middleware.
I've tried to trigger the response handlers in the middleware myself, but that doesn't seem to work at all, so I've got a simply javascript file that parses out the returned claims and POSTs them to a controller action for processing.
Problem is, even when I get them on the server side I can't parse them correctly. The error I get looks like this:
IDX10500: Signature validation failed. Unable to resolve
SecurityKeyIdentifier: 'SecurityKeyIdentifier
(
IsReadOnly = False,
Count = 1,
Clause[0] = System.IdentityModel.Tokens.NamedKeySecurityKeyIdentifierClause
),
token: '{
"alg":"RS256",
"kid":"073a3204ec09d050f5fd26460d7ddaf4b4ec7561"
}.
{
"iss":"accounts.google.com",
"sub":"100330116539301590598",
"azp":"1061880999501-b47blhmmeprkvhcsnqmhfc7t20gvlgfl.apps.googleusercontent.com",
"nonce":"7c8c3656118e4273a397c7d58e108eb1",
"email_verified":true,
"aud":"1061880999501-b47blhmmeprkvhcsnqmhfc7t20gvlgfl.apps.googleusercontent.com",
"iat":1429556543,"exp\":1429560143
}'."
}
My token verification code follows the example outlined by the good people developing IdentityServer
private async Task<IEnumerable<Claim>> ValidateIdentityTokenAsync(string idToken, string state)
{
// New Stuff
var token = new JwtSecurityToken(idToken);
var jwtHandler = new JwtSecurityTokenHandler();
byte[][] certBytes = getGoogleCertBytes();
for (int i = 0; i < certBytes.Length; i++)
{
var certificate = new X509Certificate2(certBytes[i]);
var certToken = new X509SecurityToken(certificate);
// Set up token validation
var tokenValidationParameters = new TokenValidationParameters();
tokenValidationParameters.ValidAudience = googleClientId;
tokenValidationParameters.IssuerSigningToken = certToken;
tokenValidationParameters.ValidIssuer = "accounts.google.com";
try
{
// Validate
SecurityToken jwt;
var claimsPrincipal = jwtHandler.ValidateToken(idToken, tokenValidationParameters, out jwt);
if (claimsPrincipal != null)
{
// Valid
idTokenStatus = "Valid";
}
}
catch (Exception e)
{
if (idTokenStatus != "Valid")
{
// Invalid?
}
}
}
return token.Claims;
}
private byte[][] getGoogleCertBytes()
{
// The request will be made to the authentication server.
WebRequest request = WebRequest.Create(
"https://www.googleapis.com/oauth2/v1/certs"
);
StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream());
string responseFromServer = reader.ReadToEnd();
String[] split = responseFromServer.Split(':');
// There are two certificates returned from Google
byte[][] certBytes = new byte[2][];
int index = 0;
UTF8Encoding utf8 = new UTF8Encoding();
for (int i = 0; i < split.Length; i++)
{
if (split[i].IndexOf(beginCert) > 0)
{
int startSub = split[i].IndexOf(beginCert);
int endSub = split[i].IndexOf(endCert) + endCert.Length;
certBytes[index] = utf8.GetBytes(split[i].Substring(startSub, endSub).Replace("\\n", "\n"));
index++;
}
}
return certBytes;
}
I know that Signature validation isn't completely necessary for JWTs but I haven't the slightest idea how to turn it off. Any ideas?
I thought I'd post my slightly improved version which uses JSON.Net to parse Googles' X509 Certificates and matches the key to use based on the "kid" (key-id). This is a bit more efficient than trying each certificate, since asymmetric crypto is usually quite expensive.
Also removed out-dated WebClient and manual string parsing code:
static Lazy<Dictionary<string, X509Certificate2>> Certificates = new Lazy<Dictionary<string, X509Certificate2>>( FetchGoogleCertificates );
static Dictionary<string, X509Certificate2> FetchGoogleCertificates()
{
using (var http = new HttpClient())
{
var json = http.GetStringAsync( "https://www.googleapis.com/oauth2/v1/certs" ).Result;
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>( json );
return dictionary.ToDictionary( x => x.Key, x => new X509Certificate2( Encoding.UTF8.GetBytes( x.Value ) ) );
}
}
JwtSecurityToken ValidateIdentityToken( string idToken )
{
var token = new JwtSecurityToken( idToken );
var jwtHandler = new JwtSecurityTokenHandler();
var certificates = Certificates.Value;
try
{
// Set up token validation
var tokenValidationParameters = new TokenValidationParameters();
tokenValidationParameters.ValidAudience = _clientId;
tokenValidationParameters.ValidIssuer = "accounts.google.com";
tokenValidationParameters.IssuerSigningTokens = certificates.Values.Select( x => new X509SecurityToken( x ) );
tokenValidationParameters.IssuerSigningKeys = certificates.Values.Select( x => new X509SecurityKey( x ) );
tokenValidationParameters.IssuerSigningKeyResolver = ( s, securityToken, identifier, parameters ) =>
{
return identifier.Select( x =>
{
if (!certificates.ContainsKey( x.Id ))
return null;
return new X509SecurityKey( certificates[ x.Id ] );
} ).First( x => x != null );
};
SecurityToken jwt;
var claimsPrincipal = jwtHandler.ValidateToken( idToken, tokenValidationParameters, out jwt );
return (JwtSecurityToken)jwt;
}
catch (Exception ex)
{
_trace.Error( typeof( GoogleOAuth2OpenIdHybridClient ).Name, ex );
return null;
}
}
The problem is the kid in the JWT whose value is the key identifier of the key was used to sign the JWT. Since you construct an array of certificates manually from the JWKs URI, you lose the key identifier information. The validation procedure however requires it.
You'll need to set tokenValidationParameters.IssuerSigningKeyResolver to a function that will return the same key that you set above in tokenValidationParameters.IssuerSigningToken. The purpose of this delegate is to instruct the runtime to ignore any 'matching' semantics and just try the key.
See this article for more information: JwtSecurityTokenHandler 4.0.0 Breaking Changes?
Edit: the code:
tokenValidationParameters.IssuerSigningKeyResolver = (token, securityToken, kid, validationParameters) => { return new X509SecurityKey(certificate); };
The folks at Microsoft posted code sample for Azure V2 B2C Preview endpoint that support OpenId Connect. See here, with the helper class OpenIdConnectionCachingSecurityTokenProvider the code is simplified as follows:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
AccessTokenFormat = new JwtFormat(new TokenValidationParameters
{
ValidAudiences = new[] { googleClientId },
}, new OpenIdConnectCachingSecurityTokenProvider("https://accounts.google.com/.well-known/openid-configuration"))});
This class is necessary because the OAuthBearer Middleware does not leverage. The OpenID Connect metadata endpoint exposed by the STS by default.
public class OpenIdConnectCachingSecurityTokenProvider : IIssuerSecurityTokenProvider
{
public ConfigurationManager<OpenIdConnectConfiguration> _configManager;
private string _issuer;
private IEnumerable<SecurityToken> _tokens;
private readonly string _metadataEndpoint;
private readonly ReaderWriterLockSlim _synclock = new ReaderWriterLockSlim();
public OpenIdConnectCachingSecurityTokenProvider(string metadataEndpoint)
{
_metadataEndpoint = metadataEndpoint;
_configManager = new ConfigurationManager<OpenIdConnectConfiguration>(metadataEndpoint);
RetrieveMetadata();
}
/// <summary>
/// Gets the issuer the credentials are for.
/// </summary>
/// <value>
/// The issuer the credentials are for.
/// </value>
public string Issuer
{
get
{
RetrieveMetadata();
_synclock.EnterReadLock();
try
{
return _issuer;
}
finally
{
_synclock.ExitReadLock();
}
}
}
/// <summary>
/// Gets all known security tokens.
/// </summary>
/// <value>
/// All known security tokens.
/// </value>
public IEnumerable<SecurityToken> SecurityTokens
{
get
{
RetrieveMetadata();
_synclock.EnterReadLock();
try
{
return _tokens;
}
finally
{
_synclock.ExitReadLock();
}
}
}
private void RetrieveMetadata()
{
_synclock.EnterWriteLock();
try
{
OpenIdConnectConfiguration config = _configManager.GetConfigurationAsync().Result;
_issuer = config.Issuer;
_tokens = config.SigningTokens;
}
finally
{
_synclock.ExitWriteLock();
}
}
}
Based on the answer from Johannes Rudolph I post my solution.
There is a compiler error in IssuerSigningKeyResolver Delegate which I had to solve.
This is my working code now:
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace QuapiNet.Service
{
public class JwtTokenValidation
{
public async Task<Dictionary<string, X509Certificate2>> FetchGoogleCertificates()
{
using (var http = new HttpClient())
{
var response = await http.GetAsync("https://www.googleapis.com/oauth2/v1/certs");
var dictionary = await response.Content.ReadAsAsync<Dictionary<string, string>>();
return dictionary.ToDictionary(x => x.Key, x => new X509Certificate2(Encoding.UTF8.GetBytes(x.Value)));
}
}
private string CLIENT_ID = "xxxxx.apps.googleusercontent.com";
public async Task<ClaimsPrincipal> ValidateToken(string idToken)
{
var certificates = await this.FetchGoogleCertificates();
TokenValidationParameters tvp = new TokenValidationParameters()
{
ValidateActor = false, // check the profile ID
ValidateAudience = true, // check the client ID
ValidAudience = CLIENT_ID,
ValidateIssuer = true, // check token came from Google
ValidIssuers = new List<string> { "accounts.google.com", "https://accounts.google.com" },
ValidateIssuerSigningKey = true,
RequireSignedTokens = true,
IssuerSigningKeys = certificates.Values.Select(x => new X509SecurityKey(x)),
IssuerSigningKeyResolver = (token, securityToken, kid, validationParameters) =>
{
return certificates
.Where(x => x.Key.ToUpper() == kid.ToUpper())
.Select(x => new X509SecurityKey(x.Value));
},
ValidateLifetime = true,
RequireExpirationTime = true,
ClockSkew = TimeSpan.FromHours(13)
};
JwtSecurityTokenHandler jsth = new JwtSecurityTokenHandler();
SecurityToken validatedToken;
ClaimsPrincipal cp = jsth.ValidateToken(idToken, tvp, out validatedToken);
return cp;
}
}
}

Categories