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?

Upvotes: 1

Views: 711

Answers (1)

user12207343
user12207343

Reputation:

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...

Upvotes: 1

Related Questions