我正在使用 ASP.NET WEB API 2 实现 REST API。我有默认的 AccountController 实现,方法是 // GET api/Account/ExternalLogin。
[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();
}
我浏览了互联网,没有发现任何适用于这种情况的东西。
我使用的网址
https_://_www.dummydomain.com:43363/api/Account/ExternalLogin?provider=Google&response_type=token&client_id=self&redirect_uri=https%3A%2F%2Fwww.dummydomain.com%3A43363%2F&state=jI4zGXuaVvHI8qf9E0Nww3qBwke0YsYwD9AORwKBj3o1
每个外部服务 (Google/FB) 都可以正常工作。我看到 AspNet.ExternalCookie 已设置,但重定向回来我没有被授权并得到
{
email:null,
hasRegistred: true,
loginProvaider: null
}
更新 1
Properties
Request
属性字典AppController
不包含MS_UserPrincipal
.
请参阅随附的屏幕截图。 属性键
Request.Properties["MS_HttpContext"]
返回:(见截图)
MS_HttpContextobject