Toggle navigation
首页
技术
骑行
羽毛球
资讯
联络我
登录
netcore使用jwt-authentication
2020-03-13
.NET Core
> 本文介绍如何在.net core中启用jwt authentication及生成token ## jwt简介 JSON Web Token(缩写 JWT),一种跨域认证解决方案,它本身包含了认证信息,所以server无需再保存session,做到无状态和方便横向扩展。 JWT 的三个部分依次如下: * Header(头部):JSON 对象,类似{"alg": "HS256","typ": "JWT"},描述类型和算法 * Payload(负载):JSON 对象,存放实际需要传递的数据,官方包含(也可以自定义数据): * iss (issuer):签发人 * exp (expiration time):过期时间 * sub (subject):主题 * aud (audience):受众 * nbf (Not Before):生效时间 * iat (Issued At):签发时间 * jti (JWT ID):编号 * Signature(签名):对前两部分的签名,防止数据篡改。 * HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret) ## .net core 使用jwt authentication 1. 提供生成jwt的方法 ```c# public Token GetAccessToken(string appID, string appSecret) { var key = System.Text.Encoding.ASCII.GetBytes("[secret]"); var handler = new JwtSecurityTokenHandler(); var descriptor = new SecurityTokenDescriptor() { Subject = new System.Security.Claims.ClaimsIdentity( new Claim[]{ new Claim(ClaimTypes.Name, appID) } ), Expires = DateTime.UtcNow.AddSeconds(_setting.Expired), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256) }; var token = handler.CreateToken(descriptor); var access_token = handler.WriteToken(token); ``` 2. 在ConfigureServices方法中,加入jwt认证 ```c# public void ConfigureServices(IServiceCollection services) { var keyBytes = System.Text.Encoding.ASCII.GetBytes("[secret]"); // services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) services.AddAuthentication(x => { x.DefaultAuthenticateScheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme; }) .AddCookie(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { IssuerSigningKey = new SymmetricSecurityKey(keyBytes), ValidateIssuerSigningKey = true, ValidateIssuer = false, ValidateAudience = false }; }); ``` 3. 测试认证请求 ```c# [Microsoft.AspNetCore.Authorization.Authorize] [Route("api/[controller]")] public class UsersController : ControllerBase { [HttpPost("[action]")] public object GetUsers([FromBody] GetUsersModel searchModel) { } } ``` 将jwt放在post请求的header中: Authorization: Bearer [jwt] 请求如上action,验证是否可以正常获取资料 ## 参考 * [JSON Web Token 入门教程](https://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html) * [ASP.NET Core 3.1 - JWT Authentication Tutorial with Example API](https://jasonwatmore.com/post/2019/10/11/aspnet-core-3-jwt-authentication-tutorial-with-example-api)
×
本文为博主原创,如需转载,请注明出处:
http://www.supperxin.com
返回博客列表