Skip to content

Instantly share code, notes, and snippets.

@mac2000
Last active May 18, 2020 11:26
Show Gist options
  • Save mac2000/ff95fc54bdc684646bb1de24ef07b333 to your computer and use it in GitHub Desktop.
Save mac2000/ff95fc54bdc684646bb1de24ef07b333 to your computer and use it in GitHub Desktop.
dotnet multiple jwt bearer

In this demo API we are configuring two jwt bearer auth

services
    .AddAuthentication() // JwtBearerDefaults.AuthenticationScheme - removed
    .AddJwtBearer("demo1", options => options.TokenValidationParameters = new TokenValidationParameters // "demo1", - added
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = false,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1111111111111111111111111111111111")) // "demo2", - added
    })
    .AddJwtBearer("demo2", options => options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = false,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("2222222222222222222222222222222222"))
    });

// default policy changed
services.AddAuthorization(options => options.DefaultPolicy = new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .AddAuthenticationSchemes("demo1", "demo2")
    .Build());

also in this API we have two dedicated endpoints (/demo1, /demo2) to generate tokens which does allow us to test if everything working like so:

$demo1 = Invoke-RestMethod http://localhost:5000/demo1
$demo2 = Invoke-RestMethod http://localhost:5000/demo2

Invoke-RestMethod http://localhost:5000/whoami -Headers @{ Authorization = "Bearer $demo1" }
Invoke-RestMethod http://localhost:5000/whoami -Headers @{ Authorization = "Bearer $demo2" }

Links

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
[ApiController]
public class DefaultController : ControllerBase
{
[HttpGet]
[Route("/ping")]
public string Ping() => "Pong";
[Authorize]
[HttpGet]
[Route("/whoami")]
public object WhoAmI() => new {
IsAuthenticated = User.Identity.IsAuthenticated,
Name = User.Identity.Name,
AuthenticationType = User.Identity.AuthenticationType
};
private string GenerateTokenFor(string demo, string secret) => new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
issuer: demo,
audience: demo,
notBefore: DateTime.UtcNow,
claims: new[] {
new Claim(ClaimTypes.Name, demo + "@acme.com"),
new Claim(ClaimTypes.Email, demo + "@acme.com")
},
expires: DateTime.UtcNow.AddDays(1),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret)), SecurityAlgorithms.HmacSha256)));
[HttpGet]
[Route("demo1")]
public string GetDemo1Token() => GenerateTokenFor("demo1", "1111111111111111111111111111111111");
[HttpGet]
[Route("demo2")]
public string GetDemo2Token() => GenerateTokenFor("demo2", "2222222222222222222222222222222222");
}
public class Startup
{
private void Single(IServiceCollection services) {
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1111111111111111111111111111111111"))
});
}
private void Multi(IServiceCollection services) {
services
.AddAuthentication() // JwtBearerDefaults.AuthenticationScheme - removed
.AddJwtBearer("demo1", options => options.TokenValidationParameters = new TokenValidationParameters // "demo1", - added
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1111111111111111111111111111111111")) // "demo2", - added
})
.AddJwtBearer("demo2", options => options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("2222222222222222222222222222222222"))
});
// default policy changed
services.AddAuthorization(options => options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("demo1", "demo2")
.Build());
}
public void ConfigureServices(IServiceCollection services)
{
// Single(services);
Multi(services);
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
}
public static class Program
{
public static void Main(string[] args) => CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args) => Host
.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>webBuilder.UseStartup<Startup>());
}
$demo1 = Invoke-RestMethod http://localhost:5000/demo1
$demo2 = Invoke-RestMethod http://localhost:5000/demo2
Invoke-RestMethod http://localhost:5000/whoami -Headers @{ Authorization = "Bearer $demo1" }
Invoke-RestMethod http://localhost:5000/whoami -Headers @{ Authorization = "Bearer $demo2" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment