三、Swagger驗證(全局token)


一、開啟Swagger驗證

啟用驗證之后再看:多了個小按鈕

 點開之后是如下界面:文本框里要如輸入從服務器獲取的Token。格式為:Bearer + 空格+token。 Bearer可以看作是一個默認的規則。

 添加配置代碼

                #region 啟用swagger驗證功能
                //添加一個必須的全局安全信息,和AddSecurityDefinition方法指定的方案名稱一致即可,CoreAPI。
                var security = new Dictionary<string, IEnumerable<string>> { { "CoreAPI", new string[] { } }, };
                options.AddSecurityRequirement(security);
                options.AddSecurityDefinition("CoreAPI", new ApiKeyScheme
                {
                    Description = "JWT授權(數據將在請求頭中進行傳輸) 在下方輸入Bearer {token} 即可,注意兩者之間有空格",
                    Name = "Authorization",//jwt默認的參數名稱
                    In = "header",//jwt默認存放Authorization信息的位置(請求頭中)
                    Type = "apiKey"
                });
                #endregion

整體部分為:

            //1、注冊服務Swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Version = "v1",
                    Title = "My API",
                    Description = "by JiaJia"
                });
                //在 Start.cs => ConfigureServices 方法中的 AddSwaggerGen 處增加 IncludeXmlComments 處理。
                options.IncludeXmlComments(string.Format("{0}/ZanLveCore.xml",
                AppDomain.CurrentDomain.BaseDirectory));

                #region 啟用swagger驗證功能
                //添加一個必須的全局安全信息,和AddSecurityDefinition方法指定的方案名稱一致即可,CoreAPI。
                var security = new Dictionary<string, IEnumerable<string>> { { "CoreAPI", new string[] { } }, };
                options.AddSecurityRequirement(security);
                options.AddSecurityDefinition("CoreAPI", new ApiKeyScheme
                {
                    Description = "JWT授權(數據將在請求頭中進行傳輸) 在下方輸入Bearer {token} 即可,注意兩者之間有空格",
                    Name = "Authorization",//jwt默認的參數名稱
                    In = "header",//jwt默認存放Authorization信息的位置(請求頭中)
                    Type = "apiKey"
                });
                #endregion

            });

 二、在Startup類中配置身份認證服務

            //添加jwt驗證:
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidIssuer = Configuration["Jwt:Issuer"],
                            ValidAudience = Configuration["Jwt:Audience"],
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
                        };
                    });

並在Configure啟動

            app.UseAuthentication(); 

配置appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Jwt": {
    "Issuer": "ZanLveCore",
    "Audience": "ZanLve",
    "SecretKey": "YupklGvHpiKbzqsKsBFVamQxXYWiNiYNxHAkcqqMYfeJpXIyerJLZGdBlTxVanUYJultDOtmQKJYgTKVrhLffeutSbxfFVbEQPe"
  }
}

返回401 身份驗證未通過

 測試二:先訪問GetJToken接口獲取token,在訪問接口

 后將獲取的token輸入到Swagger的文本框中:Bearer +空格+Token

 點擊確認

GetToken代碼

        /// <summary>
        /// GetToken
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string GetToken(string user, string password)
        {
            //驗證用戶名和密碼
            var claims = new Claim[] {
                new Claim(ClaimTypes.Name, "John"),
                new Claim(JwtRegisteredClaimNames.Email, "john.doe@blinkingcaret.com")
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
              //頒發者
              issuer: _config["Jwt:Issuer"],
              //接收者
              audience: _config["Jwt:Audience"],
              //添加claims
              claims: claims,
              //指定token的生命周期,過期時間
              expires: DateTime.Now.AddMinutes(30),
              //簽名證書
              signingCredentials: creds);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

注意:必須指定token過期時間(即便你不驗證token的時間)不然,請求獲取的token是不會變的(固定值的token)

 

 

 

 

 


免責聲明!

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



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