0

If a user signs in thru my GUI, all is well.

  1. I use SignInManager to sign them in.
  2. I create some claims.
  3. I create a JwtSecurityToken with the claims attached.
  4. I return JWT to client and they use it in header of future Http requests.

I have created a 'Provider' that accesses some of those claims on behalf of backend services. Those backend services are injected with the provider. When the service wants to know some info about the claim it asks the provider, which accesses the HttpContext, extracts claims and provides the requested value to the backend service. It works well.

My challenge is that I have now added a SeedData routine that is called during startup. It will create a user and then seed some business data (in the context of that new user).

The problem I have is that because this has not come from a client request, my HttpContext is NULL during SeedData routine called from startup.cs.

I have tried (within SeedData) to

// Sign in User
SignInResult signInResult = await signInManager.PasswordSignInAsync("username", "password", false, false);

// Create Claim
CustomClaim claim = new CustomClaim();
claim.ValueForBackend = "Foo";

// Add to Claims List
List<Claim> claims = new List<Claim>();
claims.Add(new Claim("custom-claim", JsonSerializer.Serialize(claim)));

// Create Claims Identity
ClaimsIdentity claimsId = new ClaimsIdentity(claims);

// Add the Claims Identity to current ClaimsPrincipal
HttpContextAccessor.HttpContext.User.AddIdentity(claimsId);

thinking that this would put the claims on the context so my provider can extract "Foo" when asked by the backend service.

However, I am getting error:

System.AggregateException: One or more errors occurred. (HttpContext must not be null.)
 ---> System.InvalidOperationException: HttpContext must not be null.
   at Microsoft.AspNetCore.Identity.SignInManager`1.get_Context()

which appears to be thrown as soon as I try the initial sign in during start-up. My take-away from this is the there is not an HttpContext during startup.cs execution.

Is there a way during startup to:

  1. Create initial user
  2. Sign In as that user
  3. Add some claims to that user
  4. Perform seeding (calling backend services) in the context of that user

I could hack around it by creating a special provider of "Foo" that does not get the value from a claim, but is instead hard-fed directly from startup.cs, but wondered if there is a way to set up an HttpContext with claims during startup.cs.

Neil W
  • 7,670
  • 3
  • 28
  • 41
  • You can see this [thread](https://stackoverflow.com/questions/53514318/auto-login-on-debug-asp-net-core-2-1) may helpful. – Yinqiu Apr 21 '21 at 02:46
  • @Yinqiu ... Excellent!! Thank you. I'd created an ugly hack around it making my provider behave differently during startup vs request handling, but the link you provided seems more elegant solution. I shall give that a go. Cheers! – Neil W Apr 21 '21 at 17:06

0 Answers0