76 lines
1.9 KiB
C#
76 lines
1.9 KiB
C#
|
|
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(); |