您需要创建一个实例FacebookAuthenticationOptions
并配置Provider
. Provider
包含一个OnAuthenticated
在您登录时触发的事件。
var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions
{
Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, ClaimValueTypes.String, "Facebook"));
return Task.FromResult(0);
}
},
// You can store these on AppSettings
AppId = ConfigurationManager.AppSettings["facebook:AppId"],
AppSecret = ConfigurationManager.AppSettings["facebook:AppSecret"]
};
app.UseFacebookAuthentication(facebookOptions);
在上面的代码中,我正在访问access_token
bycontext.AccessToken
并将其添加到Claims
当前登录用户的位置。
要稍后访问此值,您需要执行以下操作:
var owinContext = HttpContext.GetOwinContext();
var authentication = owinContext.Authentication;
var user = autentication.User;
var claim = (user.Identity as ClaimsIdentity).FindFirst("urn:facebook:access_token");
string accessToken;
if (claim != null)
accessToken = claim.Value;
为了简化这一切,你可以创建一个BaseController
并让你的所有东西都Controllers
继承自它。
BaseController
代码将是:
public class BaseController : Controller
{
public IOwinContext CurrentOwinContext
{
get
{
return HttpContext.GetOwinContext();
}
}
public IAuthenticationManager Authentication
{
get
{
return CurrentOwinContext.Authentication;
}
}
public new ClaimsPrincipal User
{
get
{
return Authentication.User;
}
}
public ClaimsIdentity Identity
{
get
{
return Authentication.User.Identity as ClaimsIdentity;
}
}
public string FacebookAccessToken
{
get
{
var claim = Identity.FindFirst("urn:facebook:access_token");
if (claim == null)
return null;
return claim.Value;
}
}
}
然后要在您的代码上获取访问令牌,您只需要访问该属性即可FacebookAccessToken
。
string accessToken = FacebookAccessToken;
可以检索一些其他值作为
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:username",
context.User.Value<string>("username"), ClaimValueTypes.String, "Facebook"));
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:name",
context.User.Value<string>("name"), ClaimValueTypes.String, "Facebook"));
请注意,并非所有字段都可用,要获取您需要的电子邮件,您需要该Scope
电子邮件。
facebookOptions.Scope.Add("email");
然后访问OnAuthenticated
事件作为
context.User.Value<string>("email");