You need to create an instance of FacebookAuthenticationOptions
and configure the Provider
. The Provider
contains an event called OnAuthenticated
which occurs when you are authenticated.
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);
}
},
// pode informar o id e secret diretamente ou incluir no AppSettings
AppId = ConfigurationManager.AppSettings["facebook:AppId"],
AppSecret = ConfigurationManager.AppSettings["facebook:AppSecret"]
};
app.UseFacebookAuthentication(facebookOptions);
In the code above I am accessing the access_token
for context.AccessToken
and adding to Claims
of the user who logged in. This is a good place to store user information while logged in.
To read this value somewhere in your code use:
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;
To simplify this whole process you can create properties in one BaseController
and make all its Controllers
inherit this new Controller
.
The BaseController
can be:
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;
}
}
}
And to use the access_token
in his Controller
you will only need access to the property FacebookAccessToken
.
string accessToken = FacebookAccessToken;
It is possible to obtain other values such as
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"));
Note that some values will not be present if the Scope
not be informed. To get the email you need to include the Scope
facebookOptions.Scope.Add("email");