feat: cookies

This commit is contained in:
2024-10-12 23:50:49 +07:00
commit 572ec9b033
20 changed files with 460 additions and 0 deletions

53
Cookie.BuiltIn/Program.cs Normal file
View File

@@ -0,0 +1,53 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/login";
});
// builder.Services.AddAuthorization();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
// app.UseAuthorization();
app.MapGet("/secured-method", /*[Authorize]*/ (HttpContext ctx) =>
{
var user = ctx.User?.FindFirst("Name");
if (user == null)
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
return user?.Value ?? "Unauthorized";
});
app.MapGet("/login", async (HttpContext ctx) =>
{
var claims = new List<Claim>();
claims.Add(new Claim("Type", "admin"));
claims.Add(new Claim("Name", "ivan"));
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var user = new ClaimsPrincipal(identity);
await ctx.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);
return "Ok";
});
app.Run();