欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.net core 3.0webapi Jwt认证

程序员文章站 2024-01-21 19:01:40
...

                                ​​​ .net core 3.0WebApi Jwt认证

1、在配置文件中appsettings.json加入Jwt配置信息

 

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Authentication": {
    "JwtBearer": {
      "JwtOption": {
        "TokenName": "token名称",
        "Issuer": "签发人",
        "Audience": "受众",
        "Expires": "2", 过期时间 
        "SigningCredentials": "签名**" 
      }
    }
  }
}

2、创建相关类

    public class JWTOption
    {
        /// <summary>
        /// Token名称
        /// </summary>
        public string TokenName { get; set; }
        /// <summary>
        /// 签发人(一般写接口请求地址)
        /// </summary>
        public string Issuer{ get; set; }
        /// <summary>
        /// 受众(一般写接口请求地址)
        /// </summary>
        public string Audience { get; set; }
        /// <summary>
        /// 超时时间 单位小时
        /// </summary>
        public int Expires { get; set; }
        /// <summary>
        /// 哈希签名的秘钥  签名 Signing 证书 Credentials
        /// </summary>
        public string SigningCredentials { get; set; }

    }

3、Startup.cs文件配置相关 验证

   public void ConfigureServices(IServiceCollection services)
        {
            var jwtOption = new JWTOption();
            Configuration.Bind("Authentication:JwtBearer:JwtOption", jwtOption);
            services.AddSingleton<JWTOption>(jwtOption);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
             {
                 options.SaveToken = true;
                 options.RequireHttpsMetadata = false;

                 options.TokenValidationParameters = new TokenValidationParameters()
                 {
                     ValidIssuer = jwtOption.Issuer,
                     ValidAudience = jwtOption.Audience,
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOption.SigningCredentials))
                 };
                 options.Events = new JwtBearerEvents
                 {
                     OnTokenValidated = context =>
                     {
                         var userInfo = context.Principal.Claims.Where(a => a.Type == jwtOption.TokenName).FirstOrDefault();
                         if (userInfo == null) context.Fail("Unauthorized");
                         else
                         {

                         }
                         return Task.CompletedTask;
                     }
                 };
             });
        }

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseFileServer();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }

4、创建token代码

  [HttpGet("Login")]
        [AllowAnonymous]
        public IActionResult GetLogin()
        {
            var claims = new[] {new Claim(_jwtOption.TokenName,"我是一个JSON")};
            var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOption.SigningCredentials));
            var token = new JwtSecurityToken(
                   issuer: _jwtOption.Issuer,
                   audience: _jwtOption.Audience,
                   expires: DateTime.Now.AddHours(_jwtOption.Expires),
                   claims: claims,
                   signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256));

            return Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                expiration = token.ValidTo,
            }); 
        }

 

相关标签: c#