简体   繁体   中英

Blazor role based authentication

There are a lot of resources online for using roles to authenticate users in a blazor application. (example: https://visualstudiomagazine.com/articles/2019/10/25/authorizing-users-in-blazor.aspx )

What's frustrating me is that none of them cover how to add users to specific role groups. If I wanted to say, authenticate everyone under a specific domain.. say all google logins with the address @example.ca

Does anyone know how to do this? Or even where to explicitly type out admin emails to add them to a specific Role group?

What's frustrating me is that none of them cover how to add users to specific role groups.

This question has nothing to do with Blazor.

Here is how you can add a registering user to a role:

[Route("api/[controller]")]
    [ApiController]
    public class AccountsController : ControllerBase
    {
        private static UserModel LoggedOutUser = new UserModel { IsAuthenticated = false };

        private readonly UserManager<IdentityUser> _userManager;

        public AccountsController(UserManager<IdentityUser> userManager)
        {
            _userManager = userManager;
        }

        [HttpPost]
        public async Task<IActionResult> Post([FromBody]RegisterModel model)
        {
            var newUser = new IdentityUser { UserName = model.Email, Email = model.Email };

            var result = await _userManager.CreateAsync(newUser, model.Password);

            if (!result.Succeeded)
            {
                var errors = result.Errors.Select(x => x.Description);

                return BadRequest(new RegisterResult { Successful = false, Errors = errors });
            }

            // Add all new users to the User role
            await _userManager.AddToRoleAsync(newUser, "User");

            // Add new users whose email starts with 'admin' to the Admin role
            if (newUser.Email.StartsWith("admin"))
            {
                await _userManager.AddToRoleAsync(newUser, "Admin");
            }

            return Ok(new RegisterResult { Successful = true });
        }
    }
}

See source and more here

If I wanted to say, authenticate everyone under a specific domain.. say all google logins with the address @example.ca

Again, this question has nothing to do with Blazor. This is a candidate for using a policy-based authentication with the requirement you've mentioned above. See the docs how to implement this, and don't hesitate to ask for help if needed.

Hope this helps...

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