【问题标题】:Store and retrieve facebook access token in ASP.NET MVC 5 app using OWIN使用 OWIN 在 ASP.NET MVC 5 应用程序中存储和检索 facebook 访问令牌
【发布时间】:2017-01-10 16:56:08
【问题描述】:

我是 OWIN 的新手。目前我正在使用 Visual Studio 2015 创建 ASP.NET MVC 项目,Visual Studio 向导处理几乎基本功能,如注册新用户、使用外部帐户登录...... 在 Startup.Auth.cs 中,我使用 facebook 功能实现了登录,如下所示:

var option = new FacebookAuthenticationOptions
        {
            AppId = appId,
            AppSecret = appSecret,
            Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = (ctx) =>
                {
                    ctx.Identity.AddClaim(new System.Security.Claims.Claim("fb_access_token", ctx.AccessToken, ClaimValueTypes.String, "Facebook"));
                    return Task.FromResult(0);
                }
            },
            AuthenticationType = DefaultAuthenticationTypes.ExternalCookie
        };
        app.UseFacebookAuthentication(option);

在 AccountController.cs 中我想获取访问令牌以获取一些用户的信息,但我总是收到声明对象的空引用异常:

public ActionResult Test()
{
    ClaimsIdentity claimIdenties = HttpContext.User.Identity as ClaimsIdentity;
    var claim = claimIdenties.FindFirst("fb_access_token");
    return View(claim.Value);
}

你们能建议我任何解决方案吗?

对不起,我英语不好

【问题讨论】:

    标签: c# asp.net facebook asp.net-mvc-5 owin


    【解决方案1】:

    在使用 facebook 注册期间..让我们将访问令牌存储在我们的数据库中以便稍后检索它们..so 在您的帐户控制器中

      var claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
                if (claimsIdentity != null)
                {
                    // Retrieve the existing claims for the user and add the FacebookAccessTokenClaim
                    var currentClaims = await UserManager.GetClaimsAsync(user.Id);
                    var facebookAccessToken = claimsIdentity.FindAll("FacebookAccessToken").First();
                    if (currentClaims.Count() <= 0)
                    {
                        await UserManager.AddClaimAsync(user.Id, facebookAccessToken);
                    }
    

    现在你可以获取访问令牌来获取类似这样的一些数据

     var fb = new FacebookClient(loginInfo.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == "FacebookAccessToken").Value);
                        dynamic userfbData = fb.Get("/me?fields=email,name");
                        picurl = String.Format("https://graph.facebook.com/{0}/picture?type=large", userfbData.id);
                        dispname = userfbData.name;
    

    这对我很有效

    【讨论】:

      猜你喜欢
      • 2012-06-04
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 2021-06-08
      • 2012-04-12
      相关资源
      最近更新 更多