How to get User Name from External Login in ASP.NET Core?

发布时间 2023-08-07 16:39:21作者: ChuckLu

How to get User Name from External Login in ASP.NET Core?

 

回答1

Do you have access to SignInManager or can you inject it? If yes, then this is how you would access user id (username), email, first & last name:

public class MyController : Microsoft.AspNetCore.Mvc.Controller
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;

    public MyController (
        UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager
    )
    {
        _userManager = userManager;
        _signInManager = signInManager;        
    }

    public async Task<IActionResult> MyAction(){
    ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();
    string userId = info.Principal.GetUserId()
    string email = info.Principal.FindFirstValue(ClaimTypes.Email);
    string FirstName = info.Principal.FindFirstValue(ClaimTypes.GivenName) ?? info.Principal.FindFirstValue(ClaimTypes.Name);
    string LastName = info.Principal.FindFirstValue(ClaimTypes.Surname);
    }
}

GetUserId extension:

public static class ClaimsPrincipalExtensions
{
    public static string GetUserId(this ClaimsPrincipal principal)
    {
        if (principal == null)
            return null; //throw new ArgumentNullException(nameof(principal));

        string ret = "";

        try
        {
            ret = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        }
        catch (System.Exception)
        {                
        }
        return ret;
    }
}