2017-08-09 57 views
0

我正在使用ASP.NET WEB API实现REST API 2.我有默认的AccountController实现方法// GET api/Account/ExternalLogin。User.Identity.IsAuthenticated总是返回false

[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(); 
} 

我已经通过互联网了解并没有发现任何适用于这种情况的东西。

URL我用

https_://_www.dummydomain.com:43363/API /帐号/ ExternalLogin提供商=谷歌& RESPONSE_TYPE =令牌&的client_id =自& REDIRECT_URI = HTTPS%3A%2F %2Fwww.dummydomain.com%3A43363%2F &状态= jI4zGXuaVvHI8qf9E0Nww3qBwke0YsYwD9AORwKBj3o1

每一个外部服务(谷歌/ FB)的作品correclty。我看到AspNet.ExternalCookie设置,但重定向回我无权在AppController得到

{ 
    email:null, 
    hasRegistred: true, 
    loginProvaider: null 
} 

更新1

Properties字典Request财产不包含MS_UserPrincipal

查看附件截图。 Properties keys

Request.Properties["MS_HttpContext"]收益:(见截图) MS_HttpContextobject

回答

0

这是无法直接在APIController使用的HttpContext属性。为了得到这个,你必须使用System.Net.Http.HttpRequestMessage类型的Request属性。 HttpRequestMessage有一个属性字典;你会发现密钥MS_UserPrincipal的值包含你的IPrincipal对象。

+0

这不适合我。 MS_UserPrincipal似乎错过了。请看截图https://www.screencast.com/t/FpMDjU1O。 –