CZGL.Auth: Quick Configuration Library for ASP.NET Core Jwt Role Authorization

2019年12月15日 2820点热度 0人点赞 0条评论
内容目录

CZGL.Auth

Found a bug that only allows one user to log in at a time, without the ability for multiple users to log in simultaneously.

Hahahahahahahahahahahahahahahahahahahahaha.

I plan to optimize it properly, fix the bug over the weekend, and do some testing before releasing it, hahahahahahahahahahahahahahaha.

New version open-source address: https://github.com/whuanle/CZGL.Auth
My code is too poor, big guys please give some guidance.

CZGL.Auth is a rapid role authorization library implemented based on Jwt. The default authorization method of ASP.Net Core Identity is Cookie. Jwt authorization only provides a basic implementation and interface, requiring one to implement role authorization and context interception themselves.

Using third-party open-source libraries like IdentityServer4 is overly complicated, with high learning and development costs.

So, in my spare time, I wrote this library.

  • Role-based authorization
  • Authorizable for each API
  • Real-time permission updates
  • Quick configuration

Usage instructions:

Search for CZGL.Auth in Nuget and install version 1.0.0, suitable for ASP.NET Core 2.x.

Injecting services

In Startup.cs

using CZGL.Auth.Services;

In ConfigureServices, inject the service

            services.AddRoleService();

Configuring services

Create a method in the Program file to configure the role authorization service before starting the website:

Use AuthBuilder to configure the authorization and authentication settings

Import

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

You can quickly configure it like this:

            new AuthBuilder()
               .Security() 
               .Jump()
               .Time(TimeSpan.FromMinutes(20))
               .DefaultRole("user")
               .End();
// No need to receive the return value, just write like this

In Security, configure the key, default user's role, Token issuer, and Token subscriber.

The key should use the text content of a private key certificate; please set a useless default role or fill in a random useless string. This role will be used when the authentication fails or for other reasons; this default role is stored in the system.

In Jump, fill in the login URL, the URL to redirect when access is unauthorized, and whether to enable the redirect feature.

If not enabled, it simply returns a 401 on failure; if enabled, it will redirect to the appropriate page when the user is not logged in or the credentials have expired.

In Time, fill in the validity period of the credentials, namely the validity time of the issued credentials, which can be in minutes or seconds. Generally, it is set to 20/30 minutes.

DefaultRole sets the default role, which is used for those who have not logged in or have invalid credentials, or if the role is deleted from the system after the credential is issued. Just fill it in randomly, ensuring it does not match the actual user role names.

Role authorization

Use RolePermission.AddRole() to add a role,

            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: Role name

Apis: APIs that the role can access

IApiPermission: Represents an API, with Name being the API name and Url being the API address.

The validation of roles and API addresses is case-insensitive.

Roles will be stored in memory, allowing you to add or remove roles at any time. For example, you can read permissions from a database and store them in the system.

For security and to avoid synchronization issues, operations are only allowed at the role level.

You can add or remove roles in RolePermission.

Login and issuing tokens

Create an AccountController API controller

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

If you do not inject AuthorizationRequirement, the issued token will be for the default user set above, which may lead to authorization issues.

Login:

        [HttpPost("Login")]
        public JsonResult Login(string username, string password)
        {
            // Check the database to see if the account password is correct and retrieve the user's role
            var user = UserModel.Users.FirstOrDefault(x => x.UserName == username && x.UserPossword == password);
            
            if (user == null)
                return new JsonResult(
                    new ResponseModel
                    {
                        Code = 0,
                        Message = "Login failed!"
                    });

            // Instantiate the class for encryption and issuing the Token
            EncryptionHash hash = new EncryptionHash();

            // Store the user identifier in the system
            _requirement.SetUserRole(user.Role);


            //// Configure user identifier
            //// Method one
            //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()),
            //};

            // Method two
            var userClaims = hash.GetClaims(username, user.Role);


            // Issue the token
            var identity = hash.GetIdentity(userClaims);
            var jwt = hash.BuildJwtToken(userClaims);
            var token = hash.BuildJwtResponseToken(jwt);


            return new JsonResult(
                new ResponseModel
                {
                    Code = 200,
                    Message = "Login successful! Please remember to save your Token credentials!",
                    Data = token
                });
        }

痴者工良

高级程序员劝退师

文章评论