如何通过ASP.NET Identity的FacebookAuthenticationProvider传递自定义声明?

Jer*_*ney 7 facebook asp.net-web-api asp.net-identity asp.net-web-api2 owin-middleware

从Visual Studio的"Web API"项目模板开始,我试图将自定义声明添加到/Api/Account/ExternalLogin端点创建的令牌.我通过FacebookAuthenticationProvider.OnAuthenticated回调添加这些,但它们不会持续到OAuthAuthorizationServerProvider.AuthorizationEndpointResponse().

注意:我使用Rahul Nath在他的文章ASP.NET Web API和外部登录中记录的类似方法- 使用社交网络进行身份验证

在我的Startup.Auth.cs类的ConfigureAuth()方法(从OwinStartup类的Configuration()方法调用)中,我向OnAuthenticated属性添加了一个回调函数,以便设置单个声明,foo其值为bar:

  var facebookAuthenticationProvider = new FacebookAuthenticationProvider() {
    OnAuthenticated = (context) => {
      context.Identity.AddClaim(new Claim("foo", "bar"));
      return Task.FromResult(0);
    }
  };
Run Code Online (Sandbox Code Playgroud)

然后我将FacebookAuthenticationProvider实例添加到一个新FacebookAuthenticationOptions对象:

  var facebookAuthenticationOptions = new FacebookAuthenticationOptions() {
    AppId = "XXXX",
    AppSecret = "YYYY",
    Provider = facebookAuthenticationProvider
  };
Run Code Online (Sandbox Code Playgroud)

并将其传递给OWIN的UseFacebookAuthentication()方法:

  app.UseFacebookAuthentication(facebookAuthenticationOptions);
Run Code Online (Sandbox Code Playgroud)

结果

如果我在OnAuthenticated回调中放置一个断点,我可以看到我的自定义声明被添加,以及许多其他声明(包括urn:facebook命名空间中的一对声明).到现在为止还挺好.

然而,当我在Facebook身份验证后通过AuthorizationEndpointResponse()我的OAuthAuthorizationServerProvider课程方法检查我的声明时,context.Identity.Claims集合中只有两个声明:

所有urn:facebook声明都已删除,我的自定义声明也已删除foo.我假设管道中的其他位置正在使用准确的声明来重新创建声明,但我不确定在哪里.

思考?

Zor*_* P. 0

我有以下用于访问自定义声明的代码:

 public class AppUser : ClaimsPrincipal{
    public AppUser(ClaimsPrincipal principal): base(principal){}
    public string Role{
        get{
            return this.FindFirst(ClaimTypes.Role).Value;
        }
    }  

    public string ProfileID{
        get{
            return this.FindFirst("ProfileID").Value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)