1
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.

Yola
  • 18,496
  • 11
  • 65
  • 106

1 Answers1

1

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();
Rena
  • 30,832
  • 6
  • 37
  • 72
  • Not sure that is what I need. I don't use Identity and EF. I will be able to do more investigation next weekend. – Yola May 26 '21 at 13:29
  • What do you mean when you say you don't use Identity? The call to `UseAuthentication` sets up ASP.NET Core Identity. – Snail Cadet May 26 '21 at 21:15
  • @SnailCadet according to [documentation](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.authappbuilderextensions.useauthentication?view=aspnetcore-5.0) it adds authentication middleware. This middleware might use Identity and might not. – Yola May 29 '21 at 13:29