feat: jwt application
This commit is contained in:
76
Jwt.Application/Program.cs
Normal file
76
Jwt.Application/Program.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
|
||||
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
var jwKey = await new HttpClient().GetStringAsync("https://localhost:5000/jwk");
|
||||
|
||||
// Add services to the container.
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddCors();
|
||||
builder.Services.AddSwaggerGen();
|
||||
builder.Services.AddAuthentication()
|
||||
.AddJwtBearer(b =>
|
||||
{
|
||||
b.TokenValidationParameters = new TokenValidationParameters()
|
||||
{
|
||||
// для облегчения дебага
|
||||
ValidateAudience = false,
|
||||
ValidateIssuer = false,
|
||||
};
|
||||
|
||||
// important
|
||||
b.Configuration = new OpenIdConnectConfiguration()
|
||||
{
|
||||
SigningKeys =
|
||||
{
|
||||
JsonWebKey.Create(jwKey)
|
||||
}
|
||||
};
|
||||
|
||||
// b.Events = new JwtBearerEvents()
|
||||
// {
|
||||
// OnMessageReceived = (ctx) =>
|
||||
// {
|
||||
// if (ctx.Request.Query.ContainsKey("token"))
|
||||
// {
|
||||
// ctx.Token = ctx.Request.Query["token"];
|
||||
// }
|
||||
//
|
||||
// return Task.CompletedTask;
|
||||
// }
|
||||
// };
|
||||
});
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseCors(p =>
|
||||
{
|
||||
p.AllowAnyOrigin();
|
||||
p.AllowAnyMethod();
|
||||
p.AllowAnyHeader();
|
||||
});
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapGet("/me", (HttpContext ctx) =>
|
||||
{
|
||||
return ctx.User.FindFirst("name").Value;
|
||||
})
|
||||
.RequireAuthorization()
|
||||
.WithName("GetWeatherForecast")
|
||||
.WithOpenApi();
|
||||
|
||||
app.Run();
|
||||
Reference in New Issue
Block a user