Search code examples
c#asp.netasp.net-coreasp.net-core-identity

SignInManager.IsSignedIn(User) versus User.Identity.IsAuthenticated


The default _LoginPartial.cshtml provided by Asp.net Core web application template is as follows.

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <form asp-controller="Account" asp-action="Logout" method="post">
        <ul >
            <li>
                <a asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
            </li>
            <li>
                <button type="submit">Log out</button>
            </li>
        </ul>
    </form>
}
else
{
    <ul >
        <li><a asp-controller="Account" asp-action="Register">Register</a></li>
        <li><a asp-controller="Account" asp-action="Login">Log in</a></li>
    </ul>
}

Rather than using the injected SignInManager.IsSignedIn(User), why don't we use User.Identity.IsAuthenticated that is much simpler? Is there any difference that I have not noticed yet?


Solution

  • IsAuthenticated works on all types of ClaimsPrincipals, which may come from ASP.NET Core Identity, or Social authentication, or AAD, or WS-Fed or whatever else.

    IsSignedIn is very specific to ASP.NET Identity.

    If you are only using ASP.NET Identity stick to IsSignedIn. If you're writing an app that can use other types of authentication then use IsAuthenticated.