How to use “User.Identity.IsAuthenticated” in Web

2020-04-08 12:58发布

问题:

User.Identity.IsAuthenticated always returns false in my ASP.NET Web API project.

In account ApiController I have following:

ClaimsIdentity identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); 
AuthenticationManager.SignIn(new AuthenticationProperties() { 
    IsPersistent = isPersistent 
}, identity);

After signing in, User.Identity.IsAuthenticated is always false in ApiController but true in MVC Controller.

回答1:

It's unable to use HttpContext property directly in APIControiller. To get this , you have to make use of Request property of type System.Net.Http.HttpRequestMessage. HttpRequestMessage has a Properties dictionary; you will find the value of the key MS_UserPrincipal holds your IPrincipal object.



回答2:

The ApiController has a User property and is available from:

base.User.Identity.IsAuthenticated


回答3:

var isAusorized = (Request.Properties["MS_HttpContext"] as HttpContextWrapper).User.Identity.IsAuthenticated;