Other account data with facebook authentication

Asked

Viewed 37 times

4

I am implementing authentication by facebook and wanted to, when entering the application with the account data, save also full name, photo, among other data.

Searching, I got the following code:

  facebookOptions.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
  {
       OnCreatingTicket = context => {
       string surName = context.User.Value<string>("last_name");
       context.Identity.AddClaim(new System.Security.Claims.Claim(ClaimTypes.Surname, surName));

       return Task.FromResult(0); 
       }
  };

The user’s last name appears in the variable surName but you won’t be safe anywhere.

If anyone can help me understand what it is Identity.AddClaim and how to save the data that comes in User.Value<T>. Thank you

1 answer

4


I was able to solve what I needed.

The code you were using in the question is not required.

It is sufficient that, in the AccountController in action ExternalLoginCallback you pass the values it contains in Claims to the model:

    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
    {
        if (remoteError != null)
        {
            ErrorMessage = $"Error from external provider: {remoteError}";
            return RedirectToAction(nameof(Login));
        }
        var info = await _signInManager.GetExternalLoginInfoAsync();
        if (info == null)
        {
            return RedirectToAction(nameof(Login));
        }

        // Sign in the user with this external login provider if the user already has a login.
        var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
            return RedirectToLocal(returnUrl);
        }
        if (result.IsLockedOut)
        {
            return RedirectToAction(nameof(Lockout));
        }
        else
        {
            // If the user does not have an account, then ask the user to create an account.
            ViewData["ReturnUrl"] = returnUrl;
            ViewData["LoginProvider"] = info.LoginProvider;
            var email = info.Principal.FindFirstValue(ClaimTypes.Email);

            //apenas esse código para pegar o valor do Name que veio do provedor
            var name = info.Principal.FindFirstValue(ClaimTypes.Name);


            return View("ExternalLogin", new ExternalLoginViewModel { Email = email, Nome = name  }); //valor da variável repassado para o model

        }
    }

Browser other questions tagged

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