Get specific login data through facebook

Asked

Viewed 625 times

2

I am seeking to implement authentication through the facebook. Where I want to get more data audiences. I already have the default authentication set up. But I need something else, because it only brings me Email.

I’m taking as a basis some answers on So-En how are:

Question with Answers by So-En

Other Article

But I couldn’t configure in my application. My Startup.Auth.Cs class is currently:

    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
            });
              app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);            
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));             

app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
            app.UseFacebookAuthentication(
               appId: "MeuAppID",
               appSecret: "MeuAppSecret");

            // O que devo setar no FacebookAppId
            // Já Coloquei o Id da app do facebook mas não funcionou

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings.Get("FacebookAppId")))
            {
                var facebookOptions = new FacebookAuthenticationOptions
                {
                    AppId = ConfigurationManager.AppSettings.Get(""),
                    AppSecret = ConfigurationManager.AppSettings.Get(""),
                    Provider = new FacebookAuthenticationProvider
                    {
                        OnAuthenticated = (context) =>
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook"));
                            foreach (var x in context.User)
                            {
                                var claimType = string.Format("urn:facebook:{0}", x.Key);
                                string claimValue = x.Value.ToString();
                                if (!context.Identity.HasClaim(claimType, claimValue))
                                    context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Facebook"));

                            }
                            return Task.FromResult(0);
                        }
                    }
                };             
                app.UseFacebookAuthentication(facebookOptions);
            }
        }

        const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
    }
}

1 answer

2


The Facebook API has undergone several changes over time, which has made most of these methods lagged.

What you can do is the following:

In his Startup.Auth.cs, add the following code:

app.UseFacebookAuthentication(new FacebookAuthenticationOptions
        {
            AppId = "*",
            AppSecret = "*",
            Provider = new FacebookAuthenticationProvider
            {
                OnAuthenticated = context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                    return Task.FromResult(true);
                }
            }
        });

With this you will return the FacebookAccessToken user’s.

The next step is to install the Facebook SDK for . NET. With this you can search the Facebook API whenever necessary.

To use, first install the package via Nuget with the following command:

Install-Package Facebook

Once done, just make the following change in your controller:

[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
    return RedirectToAction("Login");
}
// Verifica se o login foi via Facebook
if (loginInfo.Login.LoginProvider == "Facebook")
{
    var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
    var access_token = identity.FindFirstValue("FacebookAccessToken");
    var fb = new FacebookClient(access_token);
    dynamic informacoesFacebook = fb.Get("/me?fields=id,cover,name,first_name,last_name,age_range,link,gender,locale,picture,email"); 

    var id = informacoesFacebook[0];
    var cover = informacoesFacebook[1];
    var name = informacoesFacebook[2];
    var first_name = informacoesFacebook[3];
    var last_name = informacoesFacebook[4];
    var age_range = informacoesFacebook[5];
    var link = informacoesFacebook[6];
    var gender = informacoesFacebook[7];
    var locale = informacoesFacebook[8];
    var picture = informacoesFacebook[9];
    var email = informacoesFacebook[10];

    loginInfo.Email = email;
}

Note that on this line you add the fields you want to return:

dynamic informacoesFacebook = fb.Get("/me?fields=id,cover,name,first_name,last_name,
           age_range,link,gender,locale,picture,email"); 

The fields you can use, you can search on Graph API Explorer. On this screen you can see all the fields you can receive from Facebook.

  • doing this implementation, I had this error: http://answall.com/q/193491/61561 is related, or I did something wrong ?

  • 1

    This error does not occur to fetch the data, but rather in the Login part that is done by Identity. In my answer i show you where to add the Return Url, and you should add the localhost:PORTA/Account/ExternalLoginCallback if you are using localhost. If you are already online, add the URI of the site in question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.