94 lines
2.7 KiB
C#
94 lines
2.7 KiB
C#
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;
|
|
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
Log.Logger = new LoggerConfiguration()
|
|
.ReadFrom.Configuration(builder.Configuration)
|
|
.CreateLogger();
|
|
|
|
builder.Services.AddMemoryCache();
|
|
builder.Services.AddHttpContextAccessor();
|
|
builder.Services.AddHttpClient();
|
|
|
|
builder.Services.AddScoped<IUserService, UserService>();
|
|
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())
|
|
{
|
|
app.UseExceptionHandler("/Error");
|
|
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
|
app.UseHsts();
|
|
}
|
|
|
|
app.UseHttpsRedirection();
|
|
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.Use(async (context, next) =>
|
|
{
|
|
if (string.IsNullOrEmpty(context.User?.Identity?.Name) &&
|
|
context.Request.Path == "/")
|
|
{
|
|
context.Response.Redirect("/Account/Login");
|
|
return;
|
|
}
|
|
|
|
await next();
|
|
});
|
|
app.MapRazorPages();
|
|
|
|
app.Run();
|