C# User.Identity.IsAuthenticated始终返回false
我正在使用ASP.NET WEB API 2实现REST API。我有默认的AccountController实现,方法为//GET API/Account/ExternalLoginC# User.Identity.IsAuthenticated始终返回false,c#,oauth,asp.net-identity,webapi2,C#,Oauth,Asp.net Identity,Webapi2,我正在使用ASP.NET WEB API 2实现REST API。我有默认的AccountController实现,方法为//GET API/Account/ExternalLogin [OverrideAuthentication] [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)] [AllowAnonymous] [Route("ExternalLogin", Name = "ExternalLogin")] pu
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
{
if (error != null)
{
return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
}
if (!User.Identity.IsAuthenticated)
{
return new ChallengeResult(provider, this);
}
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
if (externalLogin == null)
{
return InternalServerError();
}
if (externalLogin.LoginProvider != provider)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
return new ChallengeResult(provider, this);
}
ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
externalLogin.ProviderKey));
bool hasRegistered = user != null;
if (hasRegistered)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
}
else
{
IEnumerable<Claim> claims = externalLogin.GetClaims();
ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
Authentication.SignIn(identity);
}
return Ok();
}
更新1
Properties
位于AppController
的Request
属性字典不包含MS\u UserPrincipal
请参阅附加的屏幕截图。
Request.Properties[“MS_HttpContext”]
返回:(参见屏幕截图)
无法在ApicController中直接使用HttpContext属性。要实现这一点,必须使用System.Net.Http.HttpRequestMessage类型的请求属性。HttpRequestMessage有一个属性字典;您将发现保存IPrincipal对象的密钥MS_UserPrincipal的值。这对我不起作用。她似乎被错过了。请看一下屏幕截图。
{
email:null,
hasRegistred: true,
loginProvaider: null
}