【问题标题】:ASP.NET WebApi User.Identity returns nullASP.NET WebApi User.Identity 返回 null
【发布时间】:2018-12-03 15:29:01
【问题描述】:

所以,我一直在尝试在 ASP.NET WebApi 2 应用程序中实现使用 Facebook 登录的功能。

但由于某种原因,当我尝试验证匿名请求时:

if (!User.Identity.IsAuthenticated)
{
    return new ChallengeResult(provider, this);
}

User 为空。

我已经在我的web.config 上将身份验证模式设置为None

Web.config:

<system.web>
   <authentication mode="None" />
   <compilation debug="true" targetFramework="4.6.1" />
   <httpRuntime targetFramework="4.6.1" />
   <customErrors mode="Off" />
</system.web>

另外,这也是我在 Startup.cs 类中为 OAuth 配置管道的方式:

public void ConfigureOAuth(IAppBuilder app) {
    app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
    OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

    facebookAuthOptions = new FacebookAuthenticationOptions() {
         AppId = "xxxxx",
         AppSecret = "xxxxxxxxxxx",
         Provider = new FacebookAuthProvider()
    };
    app.UseFacebookAuthentication(facebookAuthOptions);
}

这就是我获得控制器的方式:

[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
[HttpGet]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null) {
    string redirectUri = string.Empty;

    // HERE: User is always null.
    if (!User.Identity.IsAuthenticated) {
        return new ChallengeResult(provider, this);
    }

    // Rest of the code removed for brevity...
}

这就是我设置开发服务器的方式:

据我所知,User.Identity 应该在 cookie 中包含登录提供程序返回的数据/声明,但用户返回 null;因此,不会触发挑战。

【问题讨论】:

    标签: c# asp.net asp.net-web-api2 owin


    【解决方案1】:

    您需要为用户设置 ClaimsPrinicpal 并在控制器中使用“AuthorizeToken”。 这基本上是在您获得 Token 时设置的。完整的机制由 Owin Pipeline 管理。

    您需要获取 Owin 上下文并取消保护令牌并将其分配给“AuthenticationTicket”。 (AuthenticationTicket 是“Microsoft.Owin.Security”中的类)

    public class AuthorizeTokenAttribute : System.Web.Http.AuthorizeAttribute
    {
          public override void OnAuthorization(HttpActionContext actionContext)
           {
              SetUserContext(actionContext.Request.GetOwinContext()
           }
    
        private bool SetUserIdentity(IOwinContext context)
        {
            AuthenticationTicket authenticationTicket = 
            Startup.OAuthBearerAuthenticationOptions.AccessTokenFormat.Unprotect(token);
    
            context.Authentication.User = new System.Security.Claims.ClaimsPrincipal();                      
            context.Authentication.User.AddIdentity(authenticationTicket.Identity);
    
    
        }
    }
    

    以上述方式为“用户”赋值后,您不会将用户设为空,并且在分配后也可以获取身份。

    【讨论】:

    • @rottencheese 觉得有用请采纳答案
    猜你喜欢
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 2015-11-26
    • 2020-01-12
    • 2017-07-22
    相关资源
    最近更新 更多