Get specific login data via facebook

2

I'm looking to implement authentication via facebook . Where I want to get more public data. I already have the default authentication set up. But I need something more, because it just brings me the Email.

I'm basing some answers on So-En as is:

Question with So-En Ans

Another Article

But I could not configure it 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";
    }
}
    
asked by anonymous 24.01.2017 / 14:18

1 answer

2

The Facebook API has gone through a number of changes over time, making most of these methods out of date.

What you can do is the following:

In your 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);
                }
            }
        });

This will return the FacebookAccessToken of the user.

The next step is to install Facebook SDK for .NET . This will allow you to search the Facebook API whenever you need it.

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

  

Install-Package Facebook

Once you've done this, just make the following change to 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 in 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 the Graph API Explorer . In this screen you can see all the fields that you can receive from Facebook.

    
24.01.2017 / 17:20