Comb jwt under .netCore -> borrowed "Zhang's philosophy"

       Before the project's useful to jwt be token authentication, but the company has been integrated with the framework of good jwt, so understanding jwt's not clear enough, there was still separated by a layer. After watching "Zhang's philosophy" jwt understanding of jwt part of it more deeply some, this article is himself a major sort of knowledge.

  1.   Jwt Introduction
  2.        swagger enabled jwt
  3.        Configuring jwt official certification 
  4.        example

       1, jwt composition

       jwt usually consists of three parts, (1) a head Header, (2) vector message payload, (3) the signed signature. No. spaced three parts e.g.

  eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

       1) Header generally consists of two parts: alg and typ

   algHash algorithm is used, such as: HMAC SHA256 or the RSA, typis the Token type, this is: the JWT, then encoded into a first portion Base64Url:

  eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
{
  "alg": "HS256",
  "typ": "JWT"
}

     2) payload JWT This part is the main information storage section, consists mostly of Claims (Statement / Information) Composition

   在JwtRegisteredClaimNames(微软预先定义的)类中包含了一些常用的信息,例如:Jti(编号)、Iat(签发时间)、Exp(过期时间)、Iss(签发人)、Aud(订阅者)等

    A simple Pyload may be like this, using the same encoding a second portion Base64Url ::

  eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.
{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

  3) signature signed by the key generating server, to verify that the generated jwt is not valid, the last generated jwt

    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

 2、Swagger中启用jwt 注意是swagger服务内部

 api文档用的是swagger,所以还需要在startup里的swagger配置中启用jwt的配置,swagger的具体配置使用就不放在这边,准备以后结合公司的方式在补充一篇。 

  在ConfigureServices下的swagger中配置jwt

          #region Swagger 

            services.AddSwaggerGen (C => 
            { 
                #region Swagger configuration 
                
                c.SwaggerDoc ( " V1 " , new new Info 
                { 
                    Version = " v0.1.0 " , 
                    the Title = " Blog.Core the API " , 
                    the Description = " Framework Documentation " 
                }); 
                var the basePath =Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
                 var XMLPath = Path.Combine (the basePath, " Blog.Core.xml " ); 
                c.IncludeXmlComments (XMLPath, to true ); // default second parameter is false, this is Notes controller, remember modified 

                var xmlModelPath = Path.Combine (the basePath, " Blog.Core.Model.xml " ); 
                c.IncludeXmlComments (xmlModelPath); 
                #endregion 

                #region open jwt the authentication swagger
                 // add header information to verify 
                var Security = new new the Dictionary < String, The IEnumerable < String >> {{ " Blog.Core " , new new  String [] {}}}; 
                c.AddSecurityRequirement (Security); 
                c.AddSecurityDefinition ( " Blog.Core " , new new ApiKeyScheme 
                { 
                    the Description = " the JWT authorization (data will be transmitted in the request header) directly enter the box below Bearer {token} (note that a space therebetween is) " , 
                    the Name = " the Authorization " , 
                    the in = " header ",
                    Type = "apiKey"
                });

                #endregion

            });

            #endregion   

       3, Configuration official jwt

       After swagger open jwt certification, you also need to configure jwt middleware (used to parse received jwt is valid), I used the default configuration official

       The configuration in appsettings.json (can be improved, there was still the configuration that is better placed (appsettings.Development.json) file according to the environment variables, according to the middle of the Development environment changes)

  "Audience": {
    "Secret": "sdfsdfsrty45634kkhllghtdgdfss345t678fs", //不要太短,请注意!!!16+
    "SecretFile": "C:\\my-file\\blog.core.audience.secret.txt",
    "Issuer": "Blog.Core",
    "Audience": "wr"
  }  

       In the configuration ConfigureServices

      #region jwt official certification 
            // key generation 
            var audienceConfig = Configuration.GetSection ( "Audience"); 
            var symmetricKeyAsBase64 audienceConfig = [ "Secret"]; // read from the configuration of the key Note: The key length must be greater than 16 bit 
            var KeyByteArray = Encoding.UTF8.GetBytes (symmetricKeyAsBase64); 
            var = signingKey new new SymmetricSecurityKey (KeyByteArray); 

            // token validation parameters 
            var tokenValidationParameters new new tokenValidationParameters = 
            { 
                ValidateIssuerSigningKey = to true, 
                IssuerSigningKey = signingKey, 
                ValidateIssuer = to true,  
                ValidIssuer = audienceConfig [ "issuer"], // issuer
                ValidateAudience = to true,
                ValidAudience = audienceConfig["Audience"],//订阅人
                ValidateLifetime = true,
                RequireExpirationTime = true,
            };

            //主要部分
            services.AddAuthentication("Bearer")
                .AddJwtBearer(option =>
                {
                    option.TokenValidationParameters = tokenValidationParameters;
                });

            #endregion

  

       In configure  configure, enable jwt official middleware

// If you want to use the official certification must be in the top ConfigureService, configure JWT authentication services (both .AddAuthentication and .AddJwtBearer indispensable) 
 app.UseAuthentication ();

  4, an example

       After configuration is completed the GetToken need to provide a server (acquired generated jwt) to the front end of the method, the need to use the interface to add authentication feature tag indicates whether it is useful to enable detection jwt

Example (the old method, after a free way to add new generation jwt, plus refreshToken, avoid token expired question):

    [Route("api/Blog")]
    [Authorize]
    public class BlogController : Controller
    {
        // GET: api/Blog/5
        [HttpGet("GetToken")]
        [AllowAnonymous]
        public string GetToken()
        {
            TokenModelJwt tokenModel = new TokenModelJwt
            {
                Role="Admin",
                Uid=1,
                Work=""
            };
            return JwtHelper.IssueJwt(tokenModel); ;
        }
    }

 

  

      /// <summary>
        /// 颁发token
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static string IssueJwt(TokenModelJwt tokenModel)
        {
            // 自己封装的 appsettign.json 操作类,看下文
            string iss = Appsettings.app(new string[] { "Audience", "Issuer" }); //iss: 签发人
            string aud = Appsettings.app(new string[] { "Audience", "Audience" });//aud: 受众
            string secret = Appsettings.app(new string[] { "Audience", "Secret" });

            var claims = new List<Claim>
                New Claim (JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString ()) // JTI:编号
            {
                new Claim (JwtRegisteredClaimNames.Iat, $ "{ new DateTimeOffset (DateTime.Now) .ToUnixTimeMilliseconds ()}"), // Iat issued time 
                // new Claim (JwtRegisteredClaimNames.Nbf, $ " {new DateTimeOffset (DateTime.Now). ToUnixTimeMilliseconds ()} "), // nbf: Effective time 
                new Claim (JwtRegisteredClaimNames.Exp, $" { new DateTimeOffset (DateTime.Now.AddSeconds (1000)) ToUnixTimeMilliseconds ()} "), // exp:. expiration time 
                / / this is the expiration time, now expired 1000 seconds, customizable, attention JWT own buffers expiration time 
                new new the Claim (JwtRegisteredClaimNames.Iss, ISS), 
                new new the Claim (JwtRegisteredClaimNames.Aud, AUD) 
            }; 
            //// may the role of a plurality of users all given; 
            . claims.AddRange (tokenModel.Role.Split ( ',') the Select (E => the Claim new new (ClaimTypes.Role and)));
            // secret key (SymmetricSecurityKey security requirements, the length of the key is too short will be reported abnormal) 

            var = Key new new SymmetricSecurityKey (Encoding.UTF8.GetBytes (Secret)); 
            var creds = new new SigningCredentials (Key, SecurityAlgorithms.HmacSha256 ); 

            var = JWT new new JwtSecurityToken ( 
                Issuer: ISS, 
                Audience: AUD, 
                Claims: Claims, 
                Expires: DateTime.Now.AddHours (. 1), 
                signingCredentials: creds); 

            var jwtHandler new new JwtSecurityTokenHandler = (); 
            var = jwtHandler.WriteToken encodedJwt (JWT); 

            return encodedJwt; 
        }

  Supplementary Appsetings class (modified more free way of introduction), remember to use the Startup inside the injection, injection method: services.AddSingleton (new Appsettings (Env.ContentRootPath));

  the AppSettings class public 
    { 
        static IConfiguration the Configuration {GET; the SET;} 
        static String the contentPath {GET; the SET;} 

        public the AppSettings (the contentPath String) 
        { 
            // If you put the configuration file is separated according to the environment variables, you can write 
            string Path = $ "{Environment.GetEnvironmentVariable appSettings. (" ASPNETCORE_ENVIRONMENT ") JSON}."; 

            // the Path String = "appsettings.json"; 

            the Configuration new new ConfigurationBuilder = () 
                .SetBasePath (the contentPath) 
                .Add (new new JsonConfigurationSource the Path = {the Path, to false = optional, = ReloadOnChange to true}) 
                .build (); 
        }

        public static string app(params string[] sections)
        {
            try
            {
                if (sections.Any())
                {
                    return Configuration[string.Join(":", sections)];
                }
            }
            catch (Exception) { }
            return "";
        }
    }

  Finally, most of the above code using the "Lao Zhang's philosophy of" Blog.Core project code, the use of individual learning, then modifies out, if infringement please contact deleted.

 

Guess you like

Origin www.cnblogs.com/sadsadfd/p/11879440.html