如何在 ASP.NET Core 中添加角色

问题描述 投票:0回答:1

我是 ASP.NET Core 新手,目前正在开发一个名为

Clinic Management
的项目。在这个项目中,我定义了三个角色:
Admin
Doctor
Patient
。我当前的挑战是使用内置
IdentityRole
类实现功能。具体来说,我想在用户首次注册时为其分配
Admin
角色,但我在这一步上遇到了困难。此外,我不确定管理这些角色的最佳实践。目前,我已将它们手动添加到
AspNetRoles
表中,但我不确定这是否是推荐的方法。这是我的
AccountController
,我应该在其中处理这个逻辑。

using ClinicManagement.Models;
using ClinicManagement.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ClinicManagement.Controllers
{
    public class AccountController : Controller
    {
        private readonly  UserManager<ApplicationUser> userManager;
        private readonly  SignInManager<ApplicationUser> signInManager;
        private readonly RoleManager<IdentityRole> roleManager;

        public AccountController(UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager, RoleManager<IdentityRole> roleManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
            this.roleManager = roleManager;
        }
   
        public IActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Copy data from RegisterViewModel to IdentityUser
                var user = new ApplicationUser
                {
                    UserName = model.Name,
                    Email = model.Email
                };

                // Store user data in AspNetUsers database table
                var result = await userManager.CreateAsync(user, model.Password);

                // If user is successfully created, sign-in the user using
                // SignInManager and redirect to index action of HomeController
                if (result.Succeeded)
                {
                  
                    await signInManager.SignInAsync(user, isPersistent: false);

                    return RedirectToAction("index", "home");
                }

                // If there are any errors, add them to the ModelState object
                // which will be displayed by the validation summary tag helper
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            await signInManager.SignOutAsync();
            return RedirectToAction("index", "home");
        }

        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(
                    model.Email, model.Password, model.RememberMe, false);

                if (result.Succeeded)
                {
                    return RedirectToAction("index", "home");
                }

                ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
            }
            return View(model);
        }
    }
}

我尝试了几件事

c# asp.net-core-mvc user-roles
1个回答
0
投票

有管理角色的官方方法https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.rolemanager-1?view=aspnetcore-7.0

您可以通过以下方式添加角色:

在程序.cs中

builder.Services.AddDefaultIdentity<IdentityUser>(...)
    .AddRoles<IdentityRole>() // Add this
    ...

在您的注册操作中

//I set in my register.cshtml.cs
public class RegisterModel : PageModel
{
    ...
    private readonly RoleManager<IdentityRole> _roleManager;

    public RegisterModel(
        ...
        RoleManager<IdentityRole> roleManager)
    {
       ...
        _roleManager = roleManager;
    }

...
//Afer user created, create the role
var role = new IdentityRole("Admin");
await _roleManager.CreateAsync(role);

//add the role to user
await _userManager.AddToRoleAsync(user, "Admin");
...

在要执行的操作上添加 [authorize] 属性

[Authorize(Roles = "Admin")]
public async Task<IActionResult> RoleCheck()
{
   ...
}

AspNetRoles 表

AspNetUserRoles 中绑定的角色

正确的角色将被通过,错误的角色将被拒绝

© www.soinside.com 2019 - 2024. All rights reserved.