ajout validation jeton jwt

This commit is contained in:
Julien LEICHER 2021-12-15 14:59:11 +01:00
parent c9b27393a0
commit 9399b6d92c
No known key found for this signature in database
GPG Key ID: BE0761B6A007EB96
4 changed files with 37 additions and 4 deletions

2
.vscode/launch.json vendored
View File

@ -33,7 +33,7 @@
"name": ".NET Core Launch (api)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"preLaunchTask": "buildapi",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Apps/HackerNet.Api/bin/Debug/net6.0/HackerNet.Api.dll",
"args": [],

View File

@ -4,19 +4,39 @@ using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
var tokenValidation = builder.Configuration
.GetSection("TokenValidation")
.Get<TokenValidation>();
builder.Services.AddHackerNetServicesEntityFramework(builder.Configuration);
builder.Services.AddControllers();
builder.Services
.AddIdentityCore<IdentityUser>()
.AddIdentityCore<IdentityUser>(o =>
{
o.Password.RequireNonAlphanumeric = false;
})
.AddRoles<IdentityRole>()
.AddSignInManager()
.AddEntityFrameworkStores<HackerContext>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer();
.AddJwtBearer(o =>
{
o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidAudience = tokenValidation.Audience,
ValidIssuer = tokenValidation.Issuer,
ValidateAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(tokenValidation.Key)),
};
});
builder.Services.AddOpenApiDocument(d =>
{
@ -37,3 +57,10 @@ app.MapGet("/", () => "Hello World!");
app.MapControllers();
app.Run();
public class TokenValidation
{
public string Audience { get; set; }
public string Issuer { get; set; }
public string Key { get; set; }
}

View File

@ -31,5 +31,6 @@ POST {{url}}/api/accounts
Content-Type: application/json
{
"username": "test",
"password": "G6:c`bzr2h#Pq;4"
}

View File

@ -7,5 +7,10 @@
},
"ConnectionStrings": {
"Default": "Data Source=../HackerNet.Web/hackernet.db"
},
"TokenValidation": {
"Audience": "https://localhost:7252/",
"Issuer": "https://localhost:7252/",
"Key": "fwjlkf989r32lkf;wk"
}
}