C
C#2y 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();
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?
10 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
sonodan.
sonodan.2y ago
Yep, a cookie called .AspNetCore.local
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
sonodan.
sonodan.2y ago
Hmmm no the ctx.User.Claims doesn't contain any claims. When I switch "local" for "cookie" in all places, it adds the claim
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega2y ago
Isnt that expected? SignInAsync doesnt take the cookie name, it takes the login auth schema which is "cookie" here
sonodan.
sonodan.2y ago
I tried this, but get this exception
sonodan.
sonodan.2y ago
ah it seems I was misunderstanding. I thought the fallback signin schema meant the type of schema, for instance cookie or JWT. I didn't realize it had to match one of the names of the schemas adding, i thought it meant the type thank you both!
Accord
Accord2y ago
Closed!
Want results from more Discord servers?
Add your server
More Posts