关于Jwt的介绍网上不少,此处不在赘述,咱们主要看看jwt的结构。web
JWT主要由三部分组成,以下:算法
HEADER.PAYLOAD.SIGNATURE
HEADER
包含token的元数据,主要是加密算法,和签名的类型,以下面的信息,说明了shell
加密的对象类型是JWT,加密算法是HMAC SHA-256数据库
{"alg":"HS256","typ":"JWT"}
而后须要经过BASE64编码后存入token中json
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Payload
主要包含一些声明信息(claim),这些声明是key-value对的数据结构。api
一般如用户名,角色等信息,过时日期等,由于是未加密的,因此不建议存放敏感信息。安全
{"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name":"admin","exp":1578645536,"iss":"webapi.cn","aud":"WebApi"}
也须要经过BASE64编码后存入token中cookie
eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDU1MzYsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9
Signature
jwt要符合jws(Json Web Signature)的标准生成一个最终的签名。把编码后的Header和Payload信息加在一块儿,而后使用一个强加密算法,如 HmacSHA256,进行加密。HS256(BASE64(Header).Base64(Payload),secret)数据结构
2_akEH40LR2QWekgjm8Tt3lesSbKtDethmJMo_3jpF4
最后生成的token以下app
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDU1MzYsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9.2_akEH40LR2QWekgjm8Tt3lesSbKtDethmJMo_3jpF4
框架:asp.net 3.1
IDE:VS2019
命令行中执行执行如下命令,建立webapix项目:
dotnet new webapi -n Webapi -o WebApi
特别注意的时,3.x默认是没有jwt的Microsoft.AspNetCore.Authentication.JwtBearer库的,因此须要手动添加NuGet Package,切换到项目所在目录,执行 .net cli命令
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version 3.1.0
建立一个简单的POCO类,用来存储签发或者验证jwt时用到的信息
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Webapi.Models { public class TokenManagement { [JsonProperty("secret")] public string Secret { get; set; } [JsonProperty("issuer")] public string Issuer { get; set; } [JsonProperty("audience")] public string Audience { get; set; } [JsonProperty("accessExpiration")] public int AccessExpiration { get; set; } [JsonProperty("refreshExpiration")] public int RefreshExpiration { get; set; } } }
而后在 appsettings.Development.json
增长jwt使用到的配置信息(若是是生成环境在appsettings.json
添加便可)
"tokenManagement": { "secret": "123456", "issuer": "webapi.cn", "audience": "WebApi", "accessExpiration": 30, "refreshExpiration": 60 }
而后再startup类的ConfigureServices方法中增长读取配置信息
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement")); var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>(); }
到目前为止,咱们完成了一些基础工做,下面再webapi中注入jwt的验证服务,并在中间件管道中启用authentication中间件。
startup类中要引用jwt验证服务的命名空间
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens;
而后在ConfigureServices
方法中添加以下逻辑
services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)), ValidIssuer = token.Issuer, ValidAudience = token.Audience, ValidateIssuer = false, ValidateAudience = false }; });
再Configure
方法中启用验证
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
上面完成了JWT验证的功能,下面就须要增长签发token的逻辑。咱们须要增长一个专门用来用户认证和签发token的控制器,命名成AuthenticationController
,同时增长一个请求的DTO类
public class LoginRequestDTO { [Required] [JsonProperty("username")] public string Username { get; set; } [Required] [JsonProperty("password")] public string Password { get; set; } }
[Route("api/[controller]")] [ApiController] public class AuthenticationController : ControllerBase { [AllowAnonymous] [HttpPost, Route("requestToken")] public ActionResult RequestToken([FromBody] LoginRequestDTO request) { if (!ModelState.IsValid) { return BadRequest("Invalid Request"); } return Ok(); } }
目前上面的控制器只实现了基本的逻辑,下面咱们要建立签发token的服务,去完成具体的业务。第一步咱们先建立对应的服务接口,命名为IAuthenticateService
public interface IAuthenticateService { bool IsAuthenticated(LoginRequestDTO request, out string token); }
接下来,实现接口
public class TokenAuthenticationService : IAuthenticateService { public bool IsAuthenticated(LoginRequestDTO request, out string token) { throw new NotImplementedException(); } }
在Startup
的ConfigureServices
方法中注册服务
services.AddScoped<IAuthenticateService, TokenAuthenticationService>();
在Controller中注入IAuthenticateService服务,并完善action
public class AuthenticationController : ControllerBase { private readonly IAuthenticateService _authService; public AuthenticationController(IAuthenticateService authService) { this._authService = authService; } [AllowAnonymous] [HttpPost, Route("requestToken")] public ActionResult RequestToken([FromBody] LoginRequestDTO request) { if (!ModelState.IsValid) { return BadRequest("Invalid Request"); } string token; if (_authService.IsAuthenticated(request, out token)) { return Ok(token); } return BadRequest("Invalid Request"); } }
正常状况,咱们都会根据请求的用户和密码去验证用户是否合法,须要链接到数据库获取数据进行校验,咱们这里为了方便,假设任何请求的用户都是合法的。
这里单独加个用户管理的服务,不在IAuthenticateService这个服务里面添加相应逻辑,主要遵循了职责单一原则
。首先和上面同样,建立一个服务接口IUserService
public interface IUserService { bool IsValid(LoginRequestDTO req); }
实现IUserService
接口
public class UserService : IUserService { //模拟测试,默认都是人为验证有效 public bool IsValid(LoginRequestDTO req) { return true; } }
一样注册到容器中
services.AddScoped<IUserService, UserService>();
接下来,就要完善TokenAuthenticationService签发token的逻辑,首先要注入IUserService 和 TokenManagement,而后实现具体的业务逻辑,这个token的生成仍是使用的Jwt的类库提供的api,具体不详细描述。
特别注意下TokenManagement的注入是已IOptions的接口类型注入的,还记得在Startpup中吗?咱们是经过配置项的方式注册TokenManagement类型的。
public class TokenAuthenticationService : IAuthenticateService { private readonly IUserService _userService; private readonly TokenManagement _tokenManagement; public TokenAuthenticationService(IUserService userService, IOptions<TokenManagement> tokenManagement) { _userService = userService; _tokenManagement = tokenManagement.Value; } public bool IsAuthenticated(LoginRequestDTO request, out string token) { token = string.Empty; if (!_userService.IsValid(request)) return false; var claims = new[] { new Claim(ClaimTypes.Name,request.Username) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var jwtToken = new JwtSecurityToken(_tokenManagement.Issuer, _tokenManagement.Audience, claims, expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration), signingCredentials: credentials); token = new JwtSecurityTokenHandler().WriteToken(jwtToken); return true; } }
准备好测试试用的APi,打上Authorize特性,代表须要受权!
[ApiController] [Route("[controller]")] [Authorize] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } }
支持咱们能够测试验证了,咱们能够使用postman来进行http请求,先启动http服务,获取url,先测试一个访问须要受权的接口,但没有携带token信息,返回是401,表示未受权
下面咱们先经过认证接口,获取token,竟然报错,查询了下,发现HS256算法的秘钥长度最新为128位,转换成字符至少16字符,以前设置的秘钥是123456,因此致使异常。
System.ArgumentOutOfRangeException: IDX10603: Decryption failed. Keys tried: 'HS256'. Exceptions caught: '128'. token: '48' (Parameter 'KeySize') at
更新秘钥
"tokenManagement": { "secret": "123456123456123456", "issuer": "webapi.cn", "audience": "WebApi", "accessExpiration": 30, "refreshExpiration": 60 }
从新发起请求,成功获取token
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDUyMDMsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9.AehD8WTAnEtklof2OJsvg0U4_o8_SjdxmwUjzAiuI-o
把token带到以前请求的api中,从新测试,成功获取数据
基于token的认证方式,让咱们构建分布式/松耦合的系统更加容易。任何地方生成的token,只有拥有相同秘钥,就能够再任何地方进行签名校验。
固然要用好jwt认证方式,还有其余安全细节须要处理,好比palyload中不能存放敏感信息,使用https的加密传输方式等等,能够根据业务实际须要再进一步安全加固!
同时咱们也发现使用token,就能够摆脱cookie的限制,因此JWT是移动app开发的首选!