BrunoRamalho
BrunoRamalho

Reputation: 1786

asp.net mvc API get facebook token

I've created an application with asp.net mvc api with users, following this tutorial. And everything works great like that. local users and facebook login works fine.

But now I'm trying to use the FacebookClient and get the user info and friends. But it asks me for the token, but is not the same token that is stored on my session or cookie.

In api controller Account, in GetExternalLogin action I have this code:

if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                   OAuthDefaults.AuthenticationType);
                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                    CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable<Claim> claims = externalLogin.GetClaims();
                ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

Here I can find the claims. But not how to use this

My question is how can I store the facebook token on my api after the login?

Upvotes: 1

Views: 1580

Answers (1)

Michael Crook
Michael Crook

Reputation: 1535

var options = new FacebookAuthenticationOptions
{
    AppId = "Your App ID",
    AppSecret = "Your App Secret",
    Provider = new FacebookAuthenticationProvider
    {
        OnAuthenticated = async context =>
        {
            // Retrieve the OAuth access token to store for subsequent API calls
            string accessToken = context.AccessToken;

            // Retrieve the username
            string facebookUserName = context.UserName;

            // You can even retrieve the full JSON-serialized user
            var serializedUser = context.User;
        }
    }
};

app.UseFacebookAuthentication(options);

For more info on how to do this stuff see here: http://www.oauthforaspnet.com/providers/facebook/ f the OnAuthenticated you could also add:

context.Identity.AddClaim(new Claim("FacebookToken", accessToken));

As I am pretty sure that at this point we have created the user and created their claims so you

Upvotes: 2

Related Questions