CZGL.Auth: ASP.NET Core Jwt角色授權快速配置庫


CZGL.Auth

發現有Bug,會導致只能有一個用戶登錄,無法多個用戶同時登錄。

哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈。

打算好好優化一下,周六周日修改Bug,做好測試再放出來,哈哈哈哈哈哈哈哈哈哈哈哈哈。

新版本開源地址:https://github.com/whuanle/CZGL.Auth
我的代碼太渣了,大佬們指點一下。

CZGL.Auth 是一個基於 Jwt 實現的快速角色授權庫,ASP.Net Core 的 Identity 默認的授權是 Cookie。而 Jwt 授權只提供了基礎實現和接口,需要自己實現角色授權和上下文攔截等。

使用第三方開源類庫,例如 IdentityServer4 ,過於復雜,學習成本和開發成本較高。

於是空閑時間,寫了這個庫。

  • 基於角色授權
  • 每個API均可授權
  • 實時更新權限
  • 快速配置

使用方法:

Nuget 中搜索 CZGL.Auth ,安裝 1.0.0版本,適用於 ASP.NET Core 2.x。

注入服務

在 Startup.cs 中

using CZGL.Auth.Services;

ConfigureServices 中,注入服務

            services.AddRoleService();

配置服務

在 Program 文件中創建一個方法,在啟動網站前配置角色授權服務:

使用 AuthBuilder 可以配置授權認證的配置

引入

using CZGL.Auth.Services;
using CZGL.Auth.Models;
using CZGL.Auth.Interface;

你可以像這樣快速配置:

            new AuthBuilder()
               .Security() 
               .Jump()
               .Time(TimeSpan.FromMinutes(20))
               .DefaultRole("user")
               .End();
// 無需接收返回值,直接這樣寫即可

Security 中配置 密鑰、默認用戶的角色、Token頒發者、Token訂閱者。

​ 密鑰應當使用私鑰證書的文本內容;請設定一個無用的默認角色或者亂填一個無用的字符串,在認證失效或其它原因是,會使用此角色;這個默認角色是存放在系統中的。

Jump 中填寫登錄URL、無權訪問時跳轉URL和是否開啟跳轉功能。

如果不開啟,則在失敗時直接返回 401 ;如果開啟,在用戶沒有登錄或憑證已經失效時,會跳轉到相應頁面。

Time 中填寫憑證失效的時間,即頒發的憑證有效時間,可以以分鍾、秒為單位。一般都是設置20/30分鍾。

DefaultRole 設置默認角色,這個默認角色是給為登錄或憑證失效時設置,或者頒發憑證后系統刪除了這個角色等使用。亂填就行,不要跟真正的用戶角色名稱一致即可。

角色授權

使用 RolePermission.AddRole() 可以增加一個角色,

            var usera = new Role()
            {
                RoleName = "supperadmin",
                Apis = new List<IApiPermission>
                {
                new ApiPermission{Name="A",Url="/api/Test/A" },
                new ApiPermission{Name="AB",Url="/api/Test/AB" },
                new ApiPermission{Name="AC",Url="/api/Test/AC" },
                new ApiPermission{Name="ABC",Url="/api/Test/ABC" }
                }
            };
            RolePermission.AddRole(usera);

RoleName :角色名稱

Apis:角色能夠訪問的API

IApiPermission:一個API,Name API名稱,Url API地址。

校驗角色和API地址時,不區分大小寫。

角色會存儲到內存中,你可以隨時添加或刪除角色。例如從數據庫中讀取權限存儲到系統中。

為了安全和避免同步問題,只允許以角色為單位操作。

RolePermission 中可以添加或刪除角色。

登錄、頒發憑證

創建 AccountController API控制器

        private readonly AuthorizationRequirement _requirement;
        public AccountController(AuthorizationRequirement requirement)
        {
            _requirement = requirement;
        }

如果你不是用 AuthorizationRequirement 注入,那么頒發的會是上面設置的默認用戶,這可能會導致授權問題。

登錄:

        [HttpPost("Login")]
        public JsonResult Login(string username, string password)
        {
            // 中數據庫中判斷賬號密碼是否正確,並獲取用戶所屬角色等角色
            var user = UserModel.Users.FirstOrDefault(x => x.UserName == username && x.UserPossword == password);
            
            if (user == null)
                return new JsonResult(
                    new ResponseModel
                    {
                        Code = 0,
                        Message = "登陸失敗!"
                    });

            // 實例化加密和頒發 Token的類
            EncryptionHash hash = new EncryptionHash();

            // 將用戶標識存儲到系統中
            _requirement.SetUserRole(user.Role);


            //// 配置用戶標識
            //// 方法一
            //var userClaims = new Claim[]
            //{
            //    new Claim(ClaimTypes.Name,user.UserName),
            //    new Claim(ClaimTypes.Role,user.Role),
            //    new Claim(ClaimTypes.Expiration,DateTime.Now.AddMinutes(TimeSpan.FromMinutes(20)).ToString()),
            //};

            // 方法二
            var userClaims = hash.GetClaims(username, user.Role);


            // 頒發 token
            var identity = hash.GetIdentity(userClaims);
            var jwt = hash.BuildJwtToken(userClaims);
            var token = hash.BuildJwtResponseToken(jwt);


            return new JsonResult(
                new ResponseModel
                {
                    Code = 200,
                    Message = "登陸成功!請注意保存你的 Token 憑證!",
                    Data = token
                });
        }


免責聲明!

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



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