Skip to content

Instantly share code, notes, and snippets.

@tpeczek
Last active May 27, 2018 10:22
Show Gist options
  • Save tpeczek/27a14c3dcfebc9f5001931b5f1e5a2cd to your computer and use it in GitHub Desktop.
Save tpeczek/27a14c3dcfebc9f5001931b5f1e5a2cd to your computer and use it in GitHub Desktop.
Supporting multiple JWA and ES256 in ASP.​NET Core JWT bearer authentication
using System;
using System.Text;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
namespace Microsoft.Extensions.DependencyInjection
{
public static class JwtBearerMultipleJwaExtensions
{
public static AuthenticationBuilder AddJwtBearerWithHs256AndEs256(this AuthenticationBuilder builder, string hs256Key, string es256PublicKey, Action<JwtBearerOptions> configureOptions)
{
return builder.AddJwtBearer(options =>
{
configureOptions(options);
options.TokenValidationParameters.IssuerSigningKeys = new SecurityKey[]
{
GetHS256IssuerSigningKey(hs256Key),
GetES256IssuerSigningKey(es256PublicKey)
};
});
}
private static SecurityKey GetHS256IssuerSigningKey(string hs256Key)
{
return new SymmetricSecurityKey(Encoding.UTF8.GetBytes(hs256Key));
}
private static SecurityKey GetES256IssuerSigningKey(string es256PublicKey)
{
Span<byte> decodedPublicKey = FromUrlBase64String(es256PublicKey);
return new ECDsaSecurityKey(ECDsa.Create(new ECParameters
{
Curve = ECCurve.NamedCurves.nistP256,
Q = new ECPoint
{
X = decodedPublicKey.Slice(1, 32).ToArray(),
Y = decodedPublicKey.Slice(33).ToArray()
}
}));
}
private static byte[] FromUrlBase64String(string input)
{
input = input.Replace('-', '+').Replace('_', '/');
while (input.Length % 4 != 0)
{
input += "=";
}
return Convert.FromBase64String(input);
}
}
}
public class Startup
{
private const string JWT_HS256_KEY = "GRQKzLUn9w59LpXEbsESa8gtJnN3hyspq7EV4J6Fz3FjBk994r";
private const string JWT_ES256_PUBLIC_KEY = "BK5sn4jfa0Jqo9MhV01oyzK2FaEHm0KqkSCuUkKr53-9cr-vBE1a9TiiBaWy7hy0eOUF1jhZnwcd3vof4wnwSw0";
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearerWithHs256AndEs256(JWT_HS256_KEY, JWT_ES256_PUBLIC_KEY, options =>
{
...
});
...
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment