Middleware 1.0
This commit is contained in:
@@ -1,4 +1,11 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Serilog;
|
||||
using System.Text;
|
||||
using WorkFlowCheck.Common.DTO;
|
||||
using WorkFlowCheck.Web.Middleware;
|
||||
using WorkFlowCheck.Web.Services;
|
||||
using WorkFlowCheck.Web.Services.Interfaces;
|
||||
|
||||
@@ -17,9 +24,26 @@ builder.Services.AddScoped<IBaseStockService, BaseStockService>();
|
||||
builder.Host.UseSerilog();
|
||||
// Add services to the container.
|
||||
builder.Services.AddRazorPages();
|
||||
builder.Services.AddSingleton<JwtService>();
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.RequireHttpsMetadata = true;
|
||||
options.SaveToken = true;
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = "https://auth.example.com",
|
||||
ValidAudience = "https://mywebapp.com",
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("super_secret_key"))
|
||||
};
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseMiddleware<JwtMiddleware>();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
@@ -34,8 +58,25 @@ app.UseStaticFiles();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapPost("/login", async ([FromBody] UserDTO userDTO, JwtService jwtService, HttpContext httpContext) =>
|
||||
{
|
||||
var token = await jwtService.AuthenticateUserAsync(userDTO);
|
||||
if (token is null) return Results.Unauthorized();
|
||||
|
||||
httpContext.Response.Cookies.Append("AuthToken", token, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict
|
||||
});
|
||||
return Results.Ok(new { Token = token });
|
||||
});
|
||||
|
||||
app.MapGet("/secure-data", [Authorize] () => "This is protected data");
|
||||
|
||||
app.MapRazorPages();
|
||||
|
||||
app.Run();
|
||||
|
||||
Reference in New Issue
Block a user