1. AspNetCore 实现JWT(使用Microsoft.AspNetCore.Authentication.JwtBearer)

概述

在AspNetCore 中实现Jwt比较简单,使用Microsoft.AspNetCore.Authentication.JwtBearer 库,再加几行代码即可.

步骤(2.x/3.x通用)

1.新建一个AspNetCore WebApi项目.
2.创建获取token的方法

    public static class JwtHelper
    {
        public  static string GeneratorToken(string username)
        {
            // 服务端密钥 一般16bit 以上
            var secret = "1234567890123456";

            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            // 加密算法
            var credentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
            // 自定义claims
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Name,username)
            };
            var token = new JwtSecurityToken(
                "issuer", // 发行者
                "audience", // 使用者
                claims,
                expires: DateTime.Now.AddMinutes(60),
                signingCredentials: credentials
                );
            return new JwtSecurityTokenHandler().WriteToken(token);
            
        }         
    }
  1. 新建一个token控制器
    public class TokenRequest
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }


    [ApiController]
    [Route("[controller]")]
    public class TokenController:ControllerBase
    {
        [HttpPost("")]
        public async Task<IActionResult> GetToken([FromBody]TokenRequest request)
        {
            // 验证用户名密码
            var token = JwtHelper.GeneratorToken(request.UserName);
            return Ok(token);
        }
    }
  1. Startup 注册和启用中间件
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddAuthentication(
                JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Events = new JwtBearerEvents()
                    {
                        OnMessageReceived = context =>
                        {
                            context.Token = context.Request.Cookies["access_token"];
                            return Task.CompletedTask;
                        }
                    };
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = "issuer",
                        ValidAudience = "audience",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567890123456"))
                    };

                });
        }


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

  1. 验证获取token

6.验证api(使用Authorize过滤器)

  • 没有token时

  • 带上token时

说明

使用 验证如下

1. 加密后的jwt token 包含三个部分,分别是包含源数据说明的HEADER、包含自定义声明信息的PAYLOAD、以及用于验证的签名签名信息 SIGNATURE

2. 在分布式生产环境中,api 和token server 分别维护各自的公钥.

posted @ 2020-10-27 11:32  aimigi  阅读(1145)  评论(0编辑  收藏  举报