55 lines
1.6 KiB
C#
55 lines
1.6 KiB
C#
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.Events
|
|
//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(); |