我是 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 中,我想获取访问 token 以获取一些用户信息,但我总是收到声明对象的空引用异常:
public ActionResult Test()
{
ClaimsIdentity claimIdenties = HttpContext.User.Identity as ClaimsIdentity;
var claim = claimIdenties.FindFirst("fb_access_token");
return View(claim.Value);
}
你们能给我一些解决方案吗?
抱歉我英语不好
最佳答案
在注册 facebook 期间..让我们的数据库中存储访问 token 以便稍后检索它们..所以在您的帐户 Controller 中
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);
}
现在你可以获得访问 token 来获取像这样的一些数据
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;
这对我来说非常有用
关于c# - 使用 OWIN 在 ASP.NET MVC 5 应用程序中存储和检索 facebook 访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39294698/