Location>code7788 >text

.net core8 using JWT authentication (with current source code)

Popularity:981 ℃/2024-09-19 11:19:41

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:.net core8 using Swagger (with current source code)

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

Step 1: Install the latest Jwt package

Package Name:

Step 2: Configure jwt in

 /*jwt forensics*/
 "JwtSetting": {
   "Issuer": "WeChat Public Number:Not Just Coders", //publisher
   "Audience": "WeChat Public Number:Not Just Coders", //subscriber
   "ExpireSeconds": 120, //Expiration time, default minutes
   "ENAlgorithm": "HS256", //secret key algorithm
   "SecurityKey": "bzsmn=Start20240913EndOverallAuth-WebApi" //secret key composition
 }

Step 3: Create the jwt parsing model

Create a folder [model] in the directory of the OverallAuth-WebApi project and create a class file

OverallAuth-WebApi structure, see previous post:.net core8 using Swagger (with current source code)

 /// <summary>
 /// jwt configuration model
/// </summary>
 public class JwtSettingModel
 {
     /// <summary>
     /// keys
/// </summary>
     public string SecurityKey { get; set; }

     /// <summary>
     /// encryption algorithm
/// </summary>
     public string ENAlgorithm { get; set; }

     /// <summary>
     /// grantor
/// </summary>
     public string Issuer { get; set; }

     /// <summary>
     /// recipient
/// </summary>
     public string Audience { get; set; }

     /// <summary>
     /// Expiration time Unit: seconds
/// </summary>
     public int ExpireSeconds { get; set; }
 }

The directory structure is as follows:

Step 4: Create Jwt, AppSettings plugin

The directory structure is as follows:

Above you can see that we have created 2 plugins, JwtPlugInUnit and AppSettingsPlugInUnit, which correspond to the parsing of the jwt and AppSettings accessory files respectively.

So let's look at the specifics of what's inside those 2 classes.

JwtPlugInUnit as follows:

/// <summary>
/// jwt plugin
/// </summary>
public static class JwtPlugInUnit
{
    /// <summary>
    /// Initialize JWT
/// </summary>
    /// <param name="services"></param>
    public static void InitJWT(this IServiceCollection services)
    {
        var jwtsetting = <JwtSettingModel>("JwtSetting");
        ()
            .AddJwtBearer(o =>
            {
                 = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = ,
                    ValidAudience = ,
                    IssuerSigningKey = new SymmetricSecurityKey(()),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ClockSkew = 
                };
            });
    }
}

AppSettingsPlugInUnit as follows:

 /// <summary>
 /// AppSettings profile plugin
/// </summary>
 public class AppSettingsPlugInUnit
 {
     /// <summary>
     /// Declaring Configuration Properties
/// </summary>
     public static IConfiguration Configuration { get; set; }

     /// <summary>
     /// constructor
/// </summary>
     static AppSettingsPlugInUnit()
     {
         Configuration = new ConfigurationBuilder()
              .Add(new JsonConfigurationSource { Path = "", ReloadOnChange = true })
              .Build();
     }

     /// <summary>
     /// Getting the object value of a configuration file
/// </summary>
     /// <param name="jsonPath">file path</param>
     /// <param name="key"></param>
     /// <returns></returns>
     public static string GetJson(string jsonPath, string key)
     {
         if (string.IsNullOrEmpty(jsonPath) || string.IsNullOrEmpty(key)) return null;
         IConfiguration config = new ConfigurationBuilder().AddJsonFile(jsonPath).Build();//json file address
         return (key).Value;//An object in json.
     }

     /// <summary>
     /// Get database connection string
/// </summary>
     /// <returns></returns>
     public static string GetMysqlConnection()
     {
         return ("MySql").Trim();
     }

     /// <summary>
     /// Get configuration model based on node name
/// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="Node"></param>
     /// <returns></returns>
     public static T GetNode<T>(string Node) where T : new()
     {
         T model = (Node).Get<T>();
         return model;

     }
 }

Step 5: Make jwt Comply with the Swagger Protocol

Since our system uses Swagger, we want jwt to adhere to the Swagger protocol, so we'll add the following code to Swagger.

/// <summary>
/// Initializing Swagger
/// </summary>
/// <param name="services"></param>
public static void InitSwagger(this IServiceCollection services)
{
    //Add swagger
    (optinos =>
    {
        typeof(ModeuleGroupEnum).GetEnumNames().ToList().ForEach(version =>
        {
            (version, new OpenApiInfo()
            {
                Title = "privilege management system",
                Version = "V2.0",
                Description = "Ask for attention. Ask for a one-click trifecta.",
                Contact = new OpenApiContact { Name = "WeChat public number author: not just code farmer b station author: I'm not a code farmer it", Url = new Uri("") }
            });

        });

        //Reflective Acquisition Interface and Method Description
        var xmlFileName = $"{().GetName().Name}.xml";
        ((, xmlFileName), true);

        //Use jwt
        ("Bearer", new OpenApiSecurityScheme
        {
            Description = "Please enter the Bearer Token in the input box below to enable JWT authentication.",
            Name = "Authorization", // Default name, cannot be changed
            In = ,
            Type = ,
            Scheme = "Bearer"
        });

        //Making swagger adhere to the jwt protocol
        (new OpenApiSecurityRequirement
         {
           {
             new OpenApiSecurityScheme
             {
                Reference = new OpenApiReference
                {
                     Type = ,
                    Id = "Bearer"
                }
             },
            new List<string>()
            }
         });

    });
}

Note: The InitSwagger method is the method to initialize Swagger, in the previous post:.net core8 using Swagger (with current source code) It is spoken of in.

Step 6: Initialize Jwt

Add the following code to Program to initialize Jwt

Step 7: Verify Jwt

Do the above steps and jwt will be ready to use.

When you see the logo in the figure, it means that jwt initialization is successful and you can use jwt authentication and other operations in the system.

Use the [[Authorize]] and [[AllowAnonymous]] features to test authentication.

Let's test the following 2 interfaces, one requires authentication and one doesn't.

[Authorize] Turn on Authentication Testing

CheckJwt interface: turn on authentication, don't pass token

As you can see, with jwt authentication turned on, the interface fails to access without passing in a token.

UnCheckJwt interface: authentication is not enabled.

The above is the configuration process of .net core8 using jwt system authentication.

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!