SignInAsync vs AuthenticateAsync

Matthias Burger picture Matthias Burger · Oct 18, 2017 · Viewed 10.7k times · Source

I finally got my login-method with JWT Token Authentication working.

Here I'm calling

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    ClaimsPrincipalFactory.CreatePrincipal(claims),
    authProps);

I also called

await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

In the example I read that I only need the SignInAsync. So I tested it and removed AuthenticateAsync. But still, User.Identity.IsAuthenticated returns true.

Is it okay to remove the AuthenticateAsync? Or do I still need it? Why does it exist? The doc-string of AuthenticateAsync only says Extension method for authenticate

Answer

Métoule picture Métoule · Jan 25, 2018

Here's a recap between all the various methods coming from the Authentification framework (for ASP.NET Core 2.0), in the order in which they're called in a typical auth flow.

ChallengeAsync

This will instruct your browser on where to go to be authenticated. For example:

  • Cookies will redirect you to your own login page (e.g. /Account/Login)
  • Azure AD will redirect you to the Microsoft login page
  • etc..

AuthenticateAsync

This step handles whatever information comes from the authentication page (where you were redirected to by the Challenge step), and uses it to create a ClaimsPrincipal instance that identify the logged in user.

That ClaimsPrincipal is then assigned to HttpContext.User.

SignInAsync

This step takes the ClaimsPrincipal built from the previous step, and persists it. The most common way is of course the cookies.

Note that based on the source code in https://github.com/aspnet/Security/, it seems to be the only way to persist the ClaimsPrincipal.

SignOutAsync

This is the reverse step of the SignIn step. It instructs the middleware to delete any persisted data.

  • Cookies will delete the stored cookie
  • Azure AD will redirect you to their Microsoft logout page
  • etc..

So to answer your question, if you already have a ClaimsPrincipal, calling AuthenticateAsync is not necessary.

In fact, it's a bit strange that you have a ClaimsPrincipal before calling AuthentificateAsync :)