C#C
C#4y ago
sonodan.

✅ Authentication with Cookies

I'm playing around with cookies to get a better understanding. My code:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication("cookie")
    .AddCookie("local");

var app = builder.Build();

app.UseAuthentication();

app.MapGet("/", () => "Hello World!");

app.MapGet("/login", async (HttpContext ctx) =>
{
    var claims = new List<Claim>();
    claims.Add(new Claim("usr", "daniel"));
    var identity = new ClaimsIdentity(claims, "local");
    var user = new ClaimsPrincipal(identity);
    await ctx.SignInAsync("local", user);
});

app.MapGet("/user-info", (HttpContext ctx) =>
{
    return ctx.User.FindFirstValue("usr") ?? "empty";
});

app.Run();


Currently, the user-info endpoint returns "empty" after getting a cookie from the login endpoint. When I changed to AddCookie("cookie"), and change the ClaimsIdentity and Signin to "cookie", it returns a claim value. I was under the impression I could name the AddCookie scheme whatever I would like. Could someone please explain?
Was this page helpful?