JWT-Security.Jwt

[删除(380066935@qq.com或微信通知)]

NetDevPack/Security.Jwt: Json Web Key Set Manager. This component automate OAuth 2.0 rotating keys, jwks_uri. Keeping you JWK in a single place, secure and give hability to support Load Balance Scenarios. (github.com)

JWT Key Management for .NET - Generate and auto rotate Cryptographic Keys for your Jwt

The goal of this project is to help your application security by Managing your JWT.

  • Auto create RSA or ECDsa keys
  • Support for JWE
  • Publish a endpoint with your public key in JWKS format
  • Support for multiple API's to consume the JWKS endpoint
  • Auto rotate key every 90 days (Best current practices for Public Key Rotation)
  • Remove old private keys after key rotation (NIST Recommendations)
  • Use recommended settings for RSA & ECDSA (RFC 7518 Recommendations)
  • Uses random number generator to generate keys for JWE with AES CBC (dotnet does not support RSA-OAEP with Aes128GCM)
  • By default Save keys in same room of ASP.NET DataProtection (The same place where ASP.NET save the keys to to cryptograph MVC cookies)

It generates Keys way better with RSA and ECDsa algorithms. Which is most recommended by RFC 7518.

Installing

dotnet add package NetDevPack.Security.Jwt.AspNetCore

Now you need to configure Startup.cs and inject IJwtService to generate tokens.

Token Configuration

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = "NetDevPack", 
        ValidAudience = "NetDevPack.AspNet.SymetricKey"
    };
});
builder.Services.AddAuthorization();
builder.Services.AddJwksManager().UseJwtValidation();
builder.Services.AddMemoryCache();

Generating Tokens:

public AuthController(IJwtService jwtService)
{
    _jwtService = jwtService;
}

private string GenerateToken(User user)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var currentIssuer = $"{ControllerContext.HttpContext.Request.Scheme}://{ControllerContext.HttpContext.Request.Host}";

    var key = _jwtService.GetCurrentSigningCredentials(); // (ECDsa or RSA) auto generated key
    var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
    {
        Issuer = currentIssuer,
        Subject = identityClaims,
        Expires = DateTime.UtcNow.AddHours(1),
        SigningCredentials = key
    });
    return tokenHandler.WriteToken(token);
}

🛡️ What is

The JSON Web Key Set (JWKS) is a set of keys which contains the public keys used to verify any JSON Web Token (JWT) issued by the authorization server. The main goal of this component is to provide a centralized store and Key Rotation of your JWK. It also provide features to generate best practices JWK. It has a plugin for IdentityServer4, giving hability to rotating jwks_uri every 90 days and auto manage your jwks_uri.

If your API or OAuth 2.0 is under Load Balance in Kubernetes, or docker swarm it's a must have component. It work in the same way DataProtection Key of ASP.NET Core.

This component generate, store and manage your JWK. It keep a centralized store to share between your instances. By default after a 3 months a new key will be generated.

You can expose the JWK through a JWKS endpoint and share it with your API's.

ℹ️ Installing

At your API install NetDevPack.Security.Jwt:

dotnet add package NetDevPack.Security.Jwt.AspNetCore

Or via the .NET Core command line interface:

    dotnet add package NetDevPack.Security.Jwt.AspNetCore

Go to your startup.cs and change Configure:

public void ConfigureServices(IServiceCollection services)
{
    services.AddJwksManager().UseJwtValidation();
}

❤️ Generating Tokens

Usually we say Jwt. But in most cases we are trying to create a Jws.

public AuthController(IJwtService jwtService)
{
    _jwtService = jwtService;
}

private string GenerateToken(User user)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var currentIssuer = $"{ControllerContext.HttpContext.Request.Scheme}://{ControllerContext.HttpContext.Request.Host}";

    var key = _jwtService.GetCurrentSigningCredentials(); // (ECDsa or RSA) auto generated key
    var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
    {
        Issuer = currentIssuer,
        Subject = identityClaims,
        Expires = DateTime.UtcNow.AddHours(1),
        SigningCredentials = key
    });
    return tokenHandler.WriteToken(token);
}

✔️ Validating Token (Jws)

Use the same service to get the current key and validate the token.

public AuthController(IJwtService jwtService)
{
    _jwtService = jwtService;
}

private string ValidateToken(string jwt)
{
    var handler = new JsonWebTokenHandler();
    var currentIssuer = $"{ControllerContext.HttpContext.Request.Scheme}://{ControllerContext.HttpContext.Request.Host}";

    var result = handler.ValidateToken(jwt,
        new TokenValidationParameters
        {
            ValidIssuer = currentIssuer,
            SigningCredentials = _jwtService.GetCurrentSigningCredentials()
        });
    
    result.IsValid.Should().BeTrue();
}

 Multiple API's - Use Jwks

One of the biggest problem at multi api's environment is about Key Management, a classical problem of cryptography: How to distribute keys in a security way? JWT with HMAC Key relies on sharing the key between many projects and people. But instead, to accomplish it NetDevPack.Security.Jwt.Core use Public Key Cryptosystem to generate your keys. So you can share you public key at https://<your_api_adrress>/jwks! While the private key only lives in one secure place.

Peace of cake 🎂

Identity API (Who emits the token)

Install NetDevPack.Security.Jwt.AspNetCore in your API that emit JWT Tokens. Change your Startup.cs:

public void Configure(IApplicationBuilder app)
{
    app.UseJwksDiscovery().UseJwtValidation();
}

Generating the token:

 private string EncodeToken(ClaimsIdentity identityClaims)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var currentIssuer = $"{ControllerContext.HttpContext.Request.Scheme}://{ControllerContext.HttpContext.Request.Host}";

    var key = _jwksService.GetCurrentSigningCredentials();
    var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
    {
        Issuer = currentIssuer,
        Subject = identityClaims,
        Expires = DateTime.UtcNow.AddHours(1),
        SigningCredentials = key
    });
    return tokenHandler.WriteToken(token);
}

Client API

Then at your Client API, which need to validate Jwt, install NetDevPack.Security.JwtExtensions. Then change your Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = true;
        x.SaveToken = true; // keep the public key at Cache for 10 min.
        x.IncludeErrorDetails = true; // <- great for debugging
        x.SetJwksOptions(new JwkOptions("https://localhost:5001/jwks"));
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...
    app.UseAuthentication();
    app.UseAuthorization();
    // ...
}

The Controller:

[Authorize]
public class IdentityController : ControllerBase
{
    public IActionResult Get()
    {
        return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
    }
}

Done 👌!

💾 Store

By default NetDevPack.Security.Jwt are stored in same place where ASP.NET Core store their Cryptographic Key Material. We use the IXmlRepository.

So every change you made at DataProtection it will apply

You can override the default behavior by adding another provider and control it under your needs.

Database

The NetDevPack.Security.Jwt package provides a mechanism for storing yor Keys to a database using EntityFramework Core.

Install

    Install-Package Jwks.Manager.Store.EntityFrameworkCore

Or via the .NET Core command line interface:

    dotnet add package Jwks.Manager.Store.EntityFrameworkCore

Add ISecurityKeyContext to your DbContext:

class MyKeysContext : DbContext, ISecurityKeyContext
{
    public MyKeysContext(DbContextOptions<MyKeysContext> options) : base(options) { }

    // This maps to the table that stores keys.
    public DbSet<SecurityKeyWithPrivate> DataProtectionKeys { get; set; }
}

Then change your confinguration at Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddJwksManager().PersistKeysToDatabaseStore<MyKeysContext>();
}

Done!

File system

The NetDevPack.Security.Jwt package provides a mechanism for storing yor Keys to filesystem.

Install

    Install-Package Jwks.Manager.Store.FileSystem

Or via the .NET Core command line interface:

    dotnet add package Jwks.Manager.Store.FileSystem

Now change your startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddJwksManager().PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp-keys\"));
}

Samples

There are few demos here

Changing Algorithm

It's possible to change default Algorithm at configuration routine.

build.Services.AddJwksManager(o =>
{
    o.Jws = Algorithm.Create(DigitalSignaturesAlgorithm.RsaSsaPssSha256);
    o.Jwe = Algorithm.Create(EncryptionAlgorithmKey.RsaOAEP).WithContentEncryption(EncryptionAlgorithmContent.Aes128CbcHmacSha256);
});

By default it uses recommended algorithms by RFC7518

build.Services.AddJwksManager(o =>
{
    o.Jws { get; set; } = Algorithm.Create(AlgorithmType.RSA, JwtType.Jws);
    o.Jwe { get; set; } = Algorithm.Create(AlgorithmType.RSA, JwtType.Jwe);
}

The Algorithm object has a list of possibilities.

Jws

Algorithms:

ShortnameName
HS256Hmac Sha256
HS384Hmac Sha384
HS512Hmac Sha512
RS256Rsa Sha256
RS384Rsa Sha384
RS512Rsa Sha512
PS256Rsa SsaPss Sha256
PS384Rsa SsaPss Sha384
PS512Rsa SsaPss Sha512
ES256Ecdsa Sha256
ES384Ecdsa Sha384
ES512Ecdsa Sha512

Jwe

Algorithms options:

ShortnameKey Management Algorithm
RSA1_5RSA1_5
RsaOAEPRSAES OAEP using
A128KWA128KW
A256KWA256KW

Encryption options

ShortnameContent Encryption Algorithm
Aes128CbcHmacSha256A128CBC-HS256
Aes192CbcHmacSha384A192CBC-HS384
Aes256CbcHmacSha512A256CBC-HS512

IdentityServer4 - Auto jwks_uri Management

NetDevPack.Security.Jwt provides IdentityServer4 key material. It auto generates and rotate key.

First install

    Install-Package NetDevPack.Security.Jwt.IdentityServer4

Or via the .NET Core command line interface:

    dotnet add package NetDevPack.Security.Jwt.IdentityServer4

Go to Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        var builder = services.AddIdentityServer()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApis())
            .AddInMemoryClients(Config.GetClients());

        services.AddJwksManager().IdentityServer4AutoJwksManager();
    }

If you wanna use Database, follow instructions to DatabaseStore instead.