Reputation: 19041
var authenticateResult = await HttpContext.AuthenticateAsync("External");
if (!authenticateResult.Succeeded) return BadRequest();
var email = authenticateResult.Principal.FindFirst(ClaimTypes.Email);
var id = _usersService.Create(email.Value);
var claimsIdentity = new ClaimsIdentity("Application");
claimsIdentity.AddClaim(new Claim("id", id.ToString()));
await HttpContext.SignInAsync("Application", new ClaimsPrincipal(claimsIdentity));
In controllers the following line throws Sequence contains no elements in controllers:
var idClaim = HttpContext.User?.Claims.Where(x => x.Type == "id").Single();
I call UseAuthentication
and UseAuthorization
in Startup
and I thought that the first snippet would set cookies and then User
would provide access to it on every client request but it doesn't work.
If I put a breakpoint right after SiginInAsync
then HttpContext.User
contains the expected claim but not in other calls.
HttpContext.Request.Cookies
is empty. In browser I see several cookies among them .AspNetCore.External
and .AspNetCore.Application
plus some antiforgery cookies.
How do I achieve having claims in User
for all requests after authentication was done?
Can it be the problem that my front-end runs on a separate port? Probably not.
Upvotes: 1
Views: 2314
Reputation: 36715
You could follow the steps below to add updated claims to HttpContext.User
:
https://stackoverflow.com/a/65319557/11398810
Then you can get claims in other request:
var idClaim = HttpContext.User?.Claims.Where(x => x.Type == "id").Single();
Upvotes: 1