Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
147 lines (124 loc) · 4.73 KB
/
Copy pathProgram.cs
File metadata and controls
147 lines (124 loc) · 4.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
using System.Security.Claims;
using AspNet.Store.EntityFramework;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using NetDevPack.Security.Jwt.Core.Interfaces;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwagger();
// Configure Database
builder.Services.AddDbContext<DbExample>(
options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services
.AddJwksManager()
.UseJwtValidation()
.PersistKeysToDatabaseStore<DbExample>();
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();
// Create database
using var scope = app.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
var db = scope.ServiceProvider.GetRequiredService<DbExample>();
await db.Database.EnsureCreatedAsync();
}
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();