asp.net core 基於角色的認證登陸


一、登陸頁面的Controller

[Authorize(Roles = "Admin,SuperAdmin")]
public class ManageController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }


        [AllowAnonymous]
        public IActionResult Login(string returnUrl = null)
        {
            _logger.LogInformation("進入登錄頁面");
            TempData["returnUrl"] = returnUrl;
            ViewBag.Msg = " ";
            return View();
        }


        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> LoginCheck(string name, string password, string returnUrl)
        {
            string loginName = Filter.FilterHTML(name);
            var account = await _context.Account.FirstOrDefaultAsync(g => g.LoginName.Equals(loginName));
            if (account == null || (!account.Password.Equals(password)))
            {
                ViewBag.Msg = "賬號或密碼有誤,請重新輸入";
                return View("Index");
            }
            else
            {
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Sid, account.Id.ToString()));
                identity.AddClaim(new Claim(ClaimTypes.Name, account.Name));
                identity.AddClaim(new Claim(ClaimTypes.Role, account.Role));
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTime.Now.AddDays(1)
                });



                if (returnUrl == null)
                {
                    returnUrl = TempData["returnUrl"]?.ToString();
                }
                if (returnUrl != null)
                {
                    return LocalRedirect(returnUrl);
                }
                else
                {
                    return RedirectToAction(nameof(HomeController.Index), "Manage");
                }
            }
        }


        [HttpGet]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("login");
        }

        [AllowAnonymous]
        public IActionResult Denied()
        {
            return View();
        }
    }

  二、配置Startup.cs的ConfigureServices方法,增加如下代碼

            //配置使用Authorize登陸認證
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                  .AddCookie(options =>
                  {
                      options.LoginPath = new PathString("/manage/login");
                      options.AccessDeniedPath = new PathString("/manage/denied");
                  }); 

  三、配置Startup.cs的Configure方法,增加如下代碼

app.UseAuthentication();//配置使用Authorize登陸認證

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM