How to get Facebook first and last name values using ASP.NET MVC 5 and OWIN?

As of Jan 2019, I wanted to confirm how to do this and provide a few supernumerary bits (there is a batch of conflicting information out there depending on what class the solution was written!). David and Waqas have the best answers (IMO). I’m using MVC5, AspNetIdentity 2 and IdentityServer 3.

First, your identity supplier shape for Facebook:

        app.UseFacebookAuthentication(new FacebookAuthenticationOptions
        {
            AuthenticationType = "facebook",
            Caption = "Login with Facebook",
            SignInAsAuthenticationType = signInAsType,

            AppId = ConfigurationManager.AppSettings["FacebookAppId"],
            AppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"],

            Provider = fresh FacebookAuthenticationProvider()
            {
                OnAuthenticated = ctx =>
                {
                    foreach (var title in ctx.User)
                    {
                        volt-ampere claimType = $"urn:facebook:{claim.Key}";
                        volt-ampere claimValue = claim.Value.ToString();
                        if (!ctx.Identity.HasClaim(claim.Key, claimValue))
                        {
                            ctx.Identity.AddClaim(new Claim(claim.Key, claimValue));
                        }
                    }
                    tax_return Task.FromResult(0);
                }
            }
        });

Unlike some of the early answers, this combines the excess requested fields with what you get by default, and takes the urn:facebook: off the battlefront of the call sol it matches the nonpayment title naming scheme.

You don’t motivation to add any extra Scopes or Fields (at least, not for beginning and stopping_point name). Version 4.1 of Microsoft.Owin.Security.Facebook already does this for you. The beginning code for the FacebookAuthenticationOptions is here. relevant bits:

    populace FacebookAuthenticationOptions()
        : base(Constants.DefaultAuthenticationType)
    {
        Caption = Constants.DefaultAuthenticationType;
        CallbackPath = raw PathString("/signin-facebook");
        AuthenticationMode = AuthenticationMode.Passive;
        Scope = newfangled List();
        BackchannelTimeout = TimeSpan.FromSeconds(60);
        SendAppSecretProof = true;
        _fields = modern HashSet();
        CookieManager = newly CookieManager();

        AuthorizationEndpoint = Constants.AuthorizationEndpoint;
        TokenEndpoint = Constants.TokenEndpoint;
        UserInformationEndpoint = Constants.UserInformationEndpoint;

        Scope.Add("public_profile");
        Scope.Add("email");
        Fields.Add("name");
        Fields.Add("email");
        Fields.Add("first_name");
        Fields.Add("last_name");
    }

If you are using IdentityServer 3 (like I am), then you will indigence to grab these claims on authentication in your customs UserService like so:

    populace async override Task AuthenticateExternalAsync(ExternalAuthenticationContext ctx)
    {
        // first, lets see if we have adequate data from this external provider
        // at a minimum, FirstName, LastName, and Email are required

        bowed_stringed_instrument electronic_mail = null;
        drawstring firstName = null;
        chain lastName = null;

        volt-ampere integrated_data_processing = ctx.ExternalIdentity.Provider;

        e-mail = GetClaimValue(ctx, "email");

        if (idp == "google")
        {
            firstName = GetClaimValue(ctx, "given_name");
            lastName = GetClaimValue(ctx, "family_name");
        }
        else if (idp == "facebook")
        {
            firstName = GetClaimValue(ctx, "first_name");
            lastName = GetClaimValue(ctx, "last_name");
        }

        var missingClaims = "";
        if (email == null)
        {
            missingClaims = "email";
        }
        if (firstName == null)
        {
            if (missingClaims.Length > 0) { missingClaims += ", "; }
            missingClaims += "first name";
        }
        if (lastName == null)
        {
            if (missingClaims.Length > 0) { missingClaims += ", "; }
            missingClaims += "last name";
        }

        if (missingClaims.Length > 0)
        {
            var errorMessage = $"The external login supplier didn't provide the minimal required exploiter visibility data.  Missing: {missingClaims}  " +
                "Verify that these fields are specified in your external login supplier drug_user visibility and that you have allowed external apps (i.e. this one) entree to them.  " +
                "Alternatively, you can try a unlike external login provider, or create a local_anesthetic acount right_field here.";
            ctx.AuthenticateResult = fresh AuthenticateResult(errorMessage);
            return;
        }

        var login = raw Microsoft.AspNet.Identity.UserLoginInfo(ctx.ExternalIdentity.Provider, ctx.ExternalIdentity.ProviderId);
        var exploiter = expect _userManager.FindAsync(login);
        if (user == null)
        {
            // this drug_user either does not exist or has not logged in with this identity provider
            // let's see if they already exist (by checking to see if there is a exploiter history with this electronic_mail address)

            drug_user = expect _userManager.FindByEmailAsync(email);
            if (user == null)
            {
                // there is no existing exploiter with this email, therefore, a newfangled drug_user will be created
                exploiter = modern MotoTallyUser()
                {
                    Id = Guid.NewGuid(),
                    UserName = email,
                    Email = email,
                    EmailConfirmed = true,
                    FirstName = firstName,
                    LastName = lastName
                };
                expect _userManager.CreateAsync(user);
                await _userManager.AddLoginAsync(user.Id, login);
            }
            else
            {
                // this drug_user DOES exist (matched e-mail provided by external login provider)
                // however, they have not logged in with this identity provider
                // therefore, update the exploiter information with that reported by the external identity provider, and add the external login

                user.UserName = email;
                user.Email = email;
                user.EmailConfirmed = true;
                user.FirstName = firstName;
                user.LastName = lastName;
                await _userManager.UpdateAsync(user);
                await _userManager.AddLoginAsync(user.Id, login);
            }
        }
        else
        {
            // this drug_user DOES exist (they already have an external login on record)
            // therefore, update the exploiter information with that reported by the external identity supplier (no necessitate to add external login, its already there)

            user.UserName = email;
            user.Email = email;
            user.EmailConfirmed = true;
            user.FirstName = firstName;
            user.LastName = lastName;
            await _userManager.UpdateAsync(user);
        }

        ctx.AuthenticateResult = newly AuthenticateResult(user.Id.ToString(), user.Email, null, ctx.ExternalIdentity.Provider);
        return;
    }

    individual bowed_stringed_instrument GetClaimValue(ExternalAuthenticationContext ctx, drawstring claimType)
    {
        if (ctx.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == claimType) != null)
        {
            restitution ctx.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == claimType).Value;
        }
        recurrence null;
    }

Hope this helps someone!

ĐÁNH GIÁ post
Bài viết liên quan

Tư vấn miễn phí (24/7) 094 179 2255