简体   繁体   中英

How to get user information in ASP.NET Core 3.1 from Azure AD B2C user store?

The ASP.NET Core 3.1 app has been created using the Visual Studio new project wizard. Mostly default options were used, however authentication was configured to use individual user accounts stored in Azure AD B2C.

The web application is scaffolded by Visual Studio, compiles, and runs just fine. And when logging in, the current user name is printed in the header using @User.Identity.Name .

After fiddling around with @User.Identity.Name , it is not clear how to access the rest of the user information or "claims" stored in AAD B2C.

What is the correct/suggested way to access user information stored in AAD B2C within an MVC controller?

You can inject UserManager in your Classes using Dependency Injection. An example is given below:

using ContactManager.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace ContactManager.Pages.Contacts
{
    public class DI_BasePageModel : PageModel
    {
        protected ApplicationDbContext Context { get; }
        protected IAuthorizationService AuthorizationService { get; }
        protected UserManager<IdentityUser> UserManager { get; }

        public DI_BasePageModel(
            ApplicationDbContext context,
            IAuthorizationService authorizationService,
            UserManager<IdentityUser> userManager) : base()
        {
            Context = context;
            UserManager = userManager;
            AuthorizationService = authorizationService;
        } 
    }
}

And, you can use FindByNameAsync or FindByIdAsync to fetch the user.

You can follow this excellent material on .NET Core 3.1 Identity .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM