Location>code7788 >text

Building a Permission Management System from 0 to 1 Series III .net8 JWT Creating Token and Using it

Popularity:123 ℃/2024-09-23 13:42:03

clarification

This article is part of the OverallAuth 2.0 series of articles, which is updated weekly with an article in the series (Complete System Development from 0 to 1).

I will try to be very detailed in this system article, so that it can be understood by novice and veteran alike.

DESCRIPTION: OverallAuth 2.0 is a simple, easy to understand and powerful Permissions + Visual Process Management system.

Use in conjunction with the previous post for better flavor:From 0 to 1 to build a rights management system series II .net8 using JWT authentication (with the current source code)

If you are interested, please follow me (*^▽^*).

Follow me. Beat me if you can't learn.

 Creating a Token

There are many factors (conditions) to create a token, in this article, the jwt configuration and the user's basic information is used as the basic factors for generating a token (the reader is free to change the factors for generating a token, depending on the system).

Create 2 methods in (written about in the previous post)

Method 1: PropValuesType method
/// <summary>
/// Reflect to get the field
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static IEnumerable<(string Name, object Value, string Type)> PropValuesType(this object obj)
{
    List<(string a, object b, string c)> result = new List<(string a, object b, string c)>();

    var type = ();
    var props = ();
    foreach (var item in props)
    {
        ((, (obj), ));
    }
    return result;
}
above method:PropValuesTypeis to get the model fields and attributes through reflection。in this article,It's for extracting login information.,writeList<Claim>,compositional generationtokenOne of the factors。
Method 2: BuildToken method
/// <summary>
/// Generate Token
/// </summary>
/// <param name="loginResult">Login Return Information</param>
/// <returns></returns>
public static LoginOutPut BuildToken(LoginInput loginResult)
{
    LoginOutPut result = new LoginOutPut();
    //Get Configuration
    var jwtsetting = <JwtSettingModel>("JwtSetting");

    //Prepare calims, record login information
    var calims = ().Select(x => new Claim(, (), )).ToList();

    //Create header
    var key = new SymmetricSecurityKey(Encoding.());
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    var header = new JwtHeader(creds);

    //Creating a payload
    var payload = new JwtPayload(, , calims, , ());

    //Creating a Token
    var token = new JwtSecurityToken(header, payload);
    var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
     = (8).ToString();
     = tokenStr;
     = ;

    return result;
}

The above method: BuildToken is the core code to create the token, it generates the token by user information + jwt configuration information, and returns information such as token, username, token expiration time and so on (readers can add more return information).

There are 2 models in BuildToken with the following structure and location:

Create the Model class to hold the models in the system.

The LoginInput model is structured as follows:

/// <summary>
/// Login Input Model
/// </summary>
public class LoginInput
{
    /// <summary>
    /// user ID
/// </summary>
    public string? UserName { get; set; }

    /// <summary>
    /// cryptographic
/// </summary>
    public string? Password { get; set; }

}

The LoginOutPut model is structured as follows:

   /// <summary>
   /// Login Input Model
/// </summary>
   public class LoginOutPut
   {
       /// <summary>
       /// user ID
/// </summary>
       public string? UserName { get; set; }

       /// <summary>
       /// cryptographic
/// </summary>
       public string? Password { get; set; }

       /// <summary>
       /// Token
       /// </summary>
       public string? Token { get; set; }

       /// <summary>
       /// Token expiration time
/// </summary>
       public string? ExpiresDate { get; set; }

   }

After doing the above, the user can generate the Token, but in order to apply the token to the system, the following operations need to be done.

Creating Module Groupings

Create 2 enumerations in as follows

Description: InBuilding a Permission Management System from 0 to 1 Series I .net8 Using Swagger (with current source code) There are instructions in the article (or follow me on Twitter).

 /// <summary>
 /// Module Grouping
/// </summary>
 public enum ModeuleGroupEnum
 {
     /// <summary>
     /// system menu
/// </summary>
     SysMenu = 1,

     /// <summary>
     /// system user
/// </summary>
     SysUser = 2,

     /// <summary>
     /// infrastructural
/// </summary>
     Base = 3,
 }

Added 2 new enumerations [System Users] and [Basic].

Creating a New Controller

Create 2 controllers: BaseController and SysUserController, with the following structure

Create the BaseController base controller, which exists to take on the role of the system needs to rewrite the methods and get the basic information of the user's bridge.

The code is as follows:

/// <summary>
/// System Foundation Module
/// </summary>
[ApiController]
[Route("api/[controller]/[action]")]
[ApiExplorerSettings(GroupName = nameof())]
[Authorize]
public class BaseController : ControllerBase
{
    /// <summary>
    /// Getting logged in personnel information
/// </summary>
    /// <returns></returns>
    [HttpGet]
    public LoginOutPut GetLoginUserMsg()
    {
        StringValues s = new StringValues();
        var auth = ("Authorization", out s);
        if (string.IsNullOrWhiteSpace(s))
            throw new Exception("Invalid login information");
        var token = new JwtSecurityTokenHandler().ReadJwtToken(().Replace($"{} ", ""));
        LoginOutPut loginResult = new()
        {
            UserName = (f =>  == "UserName").Value,
            Password = ((f =>  == "Password").Value),
        };
        return loginResult;

    }
}

To decipher the method: get the Token in Headers, then use jwt to reverse-parse the token to get the user's basic information recorded in the BuildToken method.

Note: The [Authorize] exists above the controller, as long as there is a controller inherits the base control [BaseController], then all the methods under that controller, need to be authenticated by jwt. If an interface does not require token authentication, add [AllowAnonymous] above the interface.

Create SysUserController controller and inherit BaseController controller, its role is to assume all the interfaces of the system user, the specific code is as follows:

 /// <summary>
 /// user module
/// </summary>
 [ApiController]
 [Route("api/[controller]/[action]")]
 [ApiExplorerSettings(GroupName = nameof())]
 public class SysUserController : BaseController
 {
     /// <summary>
     /// Get Token
/// </summary>
     /// <param name="userName">user ID</param>
     /// <param name="password">cryptographic</param>
     [HttpGet]
     [AllowAnonymous]
     public string GetToken(string userName, string password)
     {
         var loginResult = (new LoginInput { UserName = userName, Password = password });

         return  ?? string.Empty;
     }
 }

As you can see, there are 2 interfaces under this controller, one for getting token interface (which can be used as login interface at the same time), and one interface for getting login person information (inheriting GetLoginUserMsg() method under BaseController).

After the above operation, jwt in the token verification is complete, look at the results.

Accessing the interface without a token will not succeed

Get the token first

Adding the use of tokens

Click Authorize to confirm use

Re-visit the GetLoginUserMsg() interface and look at the results

Responding to comments

Previous Post:From 0 to 1 to build a rights management system series II .net8 using JWT authentication (with the current source code)It got more comments, both corrective and questionable.

First of all, thank you for reading, for the corrections, and for the questions.

I'll respond to some of the questions here, as follows:

Response one:

Indeed, when .net core was first released, everyone was guided by Microsoft to this open-source framework, which everyone called .net core , and its emergence also brought c# to the brink of life and death, to gain a ray of hope. But after .net core 3.1 (supposedly), it was renamed to .net5 .net8, and so on.

Reply II:

jwt it is lightweight library, all it is in this area of processing, not very good. So it is recommended to add new middleware to verify expired token or store Token in database or cache as a way to operate complex authentication verification.

Response Three:

Ait these 2 friends, you want to come, by the way, begging to follow the blog park, follow the public number of WeChat, do not miss every update.

Thank you for your patience in watching.

If it's helpful to you, please follow me on wechat(*^▽^*).

Source code address: /yangguangchenjie/overall-auth2.0-web-api

Help me Star, please.

If you are interested, please pay attention to my weibo public number (*^▽^*).

Follow me: a full-stack multi-terminal treasure blogger, regularly sharing technical articles, irregularly sharing open source projects. Follow me to bring you to know a different program world!