Skip to content

Commit

Permalink
feat: new demos [skip ci]
Browse files Browse the repository at this point in the history
  • Loading branch information
brunobritodev committed Jan 10, 2023
1 parent f364d0a commit a0a5f62
Show file tree
Hide file tree
Showing 37 changed files with 940 additions and 87 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@

<ItemGroup>
<PackageReference Include="Bogus" Version="34.0.2" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.25.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\NetDevPack.Security.Jwt.AspNetCore\NetDevPack.Security.Jwt.AspNetCore.csproj" />
<ProjectReference Include="..\..\src\NetDevPack.Security.Jwt.Core\NetDevPack.Security.Jwt.Core.csproj" />
<ProjectReference Include="..\..\src\NetDevPack.Security.Jwt.Store.EntityFrameworkCore\NetDevPack.Security.Jwt.Store.EntityFrameworkCore.csproj" />
</ItemGroup>

</Project>
48 changes: 48 additions & 0 deletions samples/1_AspNet.Default/CustosDemoSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Security.Claims;
using Bogus;
using Microsoft.OpenApi.Models;

namespace AspNet.Default
{
public static class FakeClaims
{
public static Faker<Claim> GenerateClaim()
{
return new Faker<Claim>().CustomInstantiator(f => new Claim(f.Internet.DomainName(), f.Lorem.Text()));
}
}

public static class CustomSwagger
{
public static void AddSwagger(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Bearer {token}",
Name = "Authorization",
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
}
}
}
138 changes: 138 additions & 0 deletions samples/1_AspNet.Default/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
using System.Security.Claims;
using AspNet.Default;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using NetDevPack.Security.Jwt.Core.Interfaces;


var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwagger();

builder.Services
.AddJwksManager() // <- Use component
.UseJwtValidation(); // <- This will instruct ASP.NET to validate the JWT token using JwksManager component


// Here we're setting a secure validation of token. Like issuer, audience.
// But instead setting a custom key, this validation was overrided by `.UseJwtValidation()`
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "https://www.devstore.academy", // <- Your website
ValidAudience = "NetDevPack.Security.Jwt.AspNet"
};
});

builder.Services.AddAuthorization();

builder.Services.AddMemoryCache();
builder.Services.AddHttpContextAccessor();

var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
IdentityModelEventSource.ShowPII = true;
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();

app.MapGet("/random-jws", async (IJwtService service) =>
{
var handler = new JsonWebTokenHandler();
var now = DateTime.Now;
var descriptor = new SecurityTokenDescriptor
{
Issuer = "https://www.devstore.academy", // <- Your website
Audience = "NetDevPack.Security.Jwt.AspNet",
IssuedAt = now,
NotBefore = now,
Expires = now.AddMinutes(60),
Subject = new ClaimsIdentity(FakeClaims.GenerateClaim().Generate(5)),
SigningCredentials = await service.GetCurrentSigningCredentials()
};
return handler.CreateToken(descriptor);
})
.WithName("Generate random JWS")
.WithTags("JWS");

app.MapGet("/random-jwe", async (IJwtService service) =>
{
var handler = new JsonWebTokenHandler();
var now = DateTime.Now;
var descriptor = new SecurityTokenDescriptor
{
Issuer = "https://www.devstore.academy",
Audience = "NetDevPack.Security.Jwt.AspNet",
IssuedAt = now,
NotBefore = now,
Expires = now.AddMinutes(5),
Subject = new ClaimsIdentity(FakeClaims.GenerateClaim().Generate(5)),
EncryptingCredentials = await service.GetCurrentEncryptingCredentials()
};
return handler.CreateToken(descriptor);
})
.WithName("Generate random JWE")
.WithTags("JWE");

app.MapGet("/validate-jws/{jws}", async (IJwtService service, string jws) =>
{
var handler = new JsonWebTokenHandler();
var result = handler.ValidateToken(jws,
new TokenValidationParameters
{
ValidIssuer = "https://www.devstore.academy",
ValidAudience = "NetDevPack.Security.Jwt.AspNet",
RequireSignedTokens = false,
IssuerSigningKey = await service.GetCurrentSecurityKey(),
});
return result.Claims;
})
.WithName("Validate JWT (In fact jws, but no one cares)")
.WithTags("Validate");


app.MapGet("/validate-jwe/{jwe}", async (IJwtService service, string jwe) =>
{
var handler = new JsonWebTokenHandler();
var result = handler.ValidateToken(jwe,
new TokenValidationParameters
{
ValidIssuer = "https://www.devstore.academy",
ValidAudience = "NetDevPack.Security.Jwt.AspNet",
RequireSignedTokens = false,
TokenDecryptionKey = await service.GetCurrentSecurityKey(),
});
return result.Claims;
})
.WithName("Validate JWE")
.WithTags("Validate");

app.MapGet("/protected-endpoint", [Authorize] ([FromServices] IHttpContextAccessor context) =>
{
return Results.Ok(context.HttpContext?.User.Claims.Select(s => new { s.Type, s.Value }));
}).WithName("Protected Endpoint")
.WithTags("Validate");

app.Run();
23 changes: 23 additions & 0 deletions samples/1_AspNet.Default/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:22354",
"sslPort": 44332
}
},
"profiles": {
"Kestrel": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7099;http://localhost:5099",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
12 changes: 12 additions & 0 deletions samples/1_AspNet.Default/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=jwks;Integrated Security=SSPI;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Bogus" Version="34.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.2" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.25.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\NetDevPack.Security.Jwt.AspNetCore\NetDevPack.Security.Jwt.AspNetCore.csproj" />
<ProjectReference Include="..\..\src\NetDevPack.Security.Jwt.Core\NetDevPack.Security.Jwt.Core.csproj" />
<ProjectReference Include="..\..\src\NetDevPack.Security.Jwt.Store.EntityFrameworkCore\NetDevPack.Security.Jwt.Store.EntityFrameworkCore.csproj" />
</ItemGroup>

</Project>
48 changes: 48 additions & 0 deletions samples/2_AspNet.Store.EntityFramework/CustomDemoSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Security.Claims;
using Bogus;
using Microsoft.OpenApi.Models;

namespace AspNet.Store.EntityFramework
{
public static class FakeClaims
{
public static Faker<Claim> GenerateClaim()
{
return new Faker<Claim>().CustomInstantiator(f => new Claim(f.Internet.DomainName(), f.Lorem.Text()));
}
}

public static class CustomSwagger
{
public static void AddSwagger(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Bearer {token}",
Name = "Authorization",
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
}
}
}
13 changes: 13 additions & 0 deletions samples/2_AspNet.Store.EntityFramework/DbExample.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using NetDevPack.Security.Jwt.Core.Model;
using NetDevPack.Security.Jwt.Store.EntityFrameworkCore;

namespace AspNet.Store.EntityFramework
{
public class DbExample : IdentityDbContext, ISecurityKeyContext
{
public DbExample(DbContextOptions<DbExample> options) : base(options) { }
public DbSet<KeyMaterial> SecurityKeys { get; set; }
}
}

0 comments on commit a0a5f62

Please sign in to comment.