随笔 - 165, 文章 - 0, 评论 - 18, 阅读 - 22万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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

Posted on   火冰·瓶  阅读(1042)  评论(0编辑  收藏  举报

一、登陆页面的Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
[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方法,增加如下代码

1
2
3
4
5
6
7
8
9
//配置使用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方法,增加如下代码

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

  

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示