我是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);
}
你们能告诉我任何解决方案吗?
抱歉,我不擅长英语
答案 0 :(得分:0)
在注册期间使用facebook ..lets存储我们数据库中的访问令牌,以便稍后检索它们。所以在您的帐户控制器中
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;
这完全适合我