加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用OWIN在ASP.NET MVC 5应用程序中存储和检索facebook访

发布时间:2020-12-15 21:01:48 所属栏目:百科 来源:网络整理
导读:我是OWIN的新手.目前我正在使用visual studio 2015来创建ASP.NET MVC项目,而visual studio向导几乎可以处理基本功能,例如注册新用户,使用外部帐户登录…… 在Startup.Auth.cs中,我用facebook功能实现了登录,如下所示: var option = new FacebookAuthenticat
我是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);
}

你们能告诉我任何解决方案吗?

对不起,我不擅长英语

解决方法

在注册facebook.com时,我们会在我们的数据库中存储访问令牌以便稍后检索它们.所以在您的帐户控制器中

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;

这对我很有用

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读