Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should HttpContext.User.Identity.IsAuthenticated and SignInManager.IsSignedIn(HttpContext.User) be used?

There seems to be some ambiguity about these 2. I use them interchangeably throughout my project and the only reason is because I couldn't figure out when to use one or the other.

What would be the cases where one is true while the other one isn't?

If I were to only use ASP.NET Identity to authenticate users, would one or the other more favourable or it doesn't really matter?

like image 367
Dealdiane Avatar asked Aug 22 '16 04:08

Dealdiane


People also ask

What is HttpContext User identity?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.

What is IsAuthenticated identity?

Obviously, User. Identity. IsAuthenticated checks to see if the User is authenticated while Request. IsAuthenticated checks to see if the Request is Authenticated.

How do you set HttpContext User identity for an application manually?

You can achieve this by manually settings HttpContext. User: var identity = new ClaimsIdentity("Custom"); HttpContext. User = new ClaimsPrincipal(identity);

Why is User identity IsAuthenticated false?

identity. isauthenticated is False when a user is already logged in.


1 Answers

  • HttpContext.User.Identity.IsAuthenticatedchecks if the current user is authenticated(true if the user was authenticated; otherwise, false.). When you set user like this: HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity("SomeAuthType")); or the request authentication is succeed for any authentication middleware(such as JwtBearer) it will be true.
  • SignInManager is a feature of aspnet identity and it checks if the principal has an identity with the application cookie identity. If you look at source code you can see : return principal?.Identities != null && principal.Identities.Any(i => i.AuthenticationType == Options.Cookies.ApplicationCookieAuthenticationScheme);.

So, if you use aspnet identity and you want to check if user is authenticated by aspnet identity middleware(by app.UseIdentity()) then use SignInManager.IsSignedIn. If you don't use aspnet identity or it is not important how the current user is authenticated then use HttpContext.User.Identity.IsAuthenticated.

like image 150
adem caglin Avatar answered Sep 22 '22 17:09

adem caglin