博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net core 基于角色的认证登陆

Posted on 2019-04-14 18:20  火冰·瓶  阅读(997)  评论(0编辑  收藏  举报

一、登陆页面的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登陆认证
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
      .AddCookie(options =>
      {
          options.SlidingExpiration = true;//不活动后注销用户
          options.ExpireTimeSpan = TimeSpan.FromMinutes(60 * 10);//不活动后注销用户的超期时间
          options.LoginPath = new PathString("/manage/login");
          options.AccessDeniedPath = new PathString("/manage/denied");
      });

  

 

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

app.UseAuthentication();//配置使用Authorize登陆认证