Search code examples
c#asp.net-corejwtasp.net-core-identityasp.net-core-2.2

Why sign-in a new user when using ASP.NET Core Identity and token-based auth?


I am using ASP.NET Core with Identity, and JWTs. There's not much info on this, as the docs don't cover Identity with JWTs, only with cookies.

Examples here and on blogs typically do this during user registration:

// ...other stuff within the controller
var result = await _userManager.CreateAsync(user, password);
if (result.Succeeded) {
  await _signInManager.SignInAsync(user, false);     // <--- ???
  return await generateJwt(email, user);
}

I expected that after creating a user, nothing more needs to be done (other than returning a jwt). Token-based auth is supposed to avoid server-side state.

So what is the purpose of using Identity's _signInManager.SignInAsync? Is it necessary?


Solution

  • So what is the purpose of using Identity's _signInManager.SignInAsync?

    This call is a thin wrapper around a call to HttpContext.SignInAsync, which looks like this:

    await Context.SignInAsync(IdentityConstants.ApplicationScheme,
        userPrincipal,
        authenticationProperties ?? new AuthenticationProperties());
    

    With all the default setup as created by a call to e.g. AddIdentity, this ends up persisting the authentication information into a cookie that's named Identity.Application.

    Is it necessary?

    In an environment where you're not using cookie-based authentication, it's not necessary. You are persisting authentication information using a JWT and so have no need for the cookie to be set.