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

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;
    }
}

 

实际使用的时候,是这样

var info = await _signInManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return RedirectToLocal("/Identity/Account/Login");
            }

            var identity = info.Principal.Identity;
            var userName = identity.Name;
            if (!identity.IsAuthenticated)
            {
                return RedirectToLocal("/Identity/Account/Login");
            }
            Console.WriteLine(userName);

 

posted @ 2023-08-07 16:34  ChuckLu  阅读(34)  评论(0)    收藏  举报