在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
该系列简单介绍了在Asp.Net Core Web API中如何使用JWT创建token进行鉴权。 1、创建Asp.Net Core Web API项目 这里使用的环境是VS2019 + .Net Core 3.1。 2、添加JWT服务 (1) 使用Nuget安装System.IdentityModel.Tokens.Jwt。 public interface IJwtService { string GetToken(string name); } using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace TestWebApi.AuthCenter.Utility { public class JwtService : IJwtService { private readonly IConfiguration _configuration; public JwtService(IConfiguration configuration) { _configuration = configuration; } public string GetToken(string name) { /** * Claims(Payload) * Claims包含了一些跟这个token有关的重要信息。JWT标准规定的字段: * * iss: The issuer of the token, 签发人 * sub: The subject of the token, 主题 * exp: Expiration Time. 过期时间(Unix时间戳格式) * iat: Issued At. 签发时间(Unix时间戳格式) * jti: JWT ID. 编号 * aud: audience. 受众 * nbf: Not Before. 生效时间 * * 除了规定的字段外,可以包含其他任何JSON兼容的字段。 * */ var claims = new[] { new Claim(ClaimTypes.Name, name), new Claim("NickName", "NetCore"), new Claim("Role", "Administrator") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"])); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: _configuration["issuer"], //签发人 audience: _configuration["audience"], claims: claims, expires: DateTime.Now.AddMinutes(20), //20分钟有效期 signingCredentials: credentials); var tokenStr = new JwtSecurityTokenHandler().WriteToken(token); return tokenStr; } } } (3) 注入JWT服务 //注入JWT服务 services.AddScoped<IJwtService, JwtService>(); 3、添加JWT配置信息(appsettings.json) "issuer": "http://localhost:9527", "audience": "http://localhost:9527", "SecurityKey": "4A9A70D2-B8AD-42E1-B002-553BDEF4E76F" 其中,SecurityKey为新建的一个GUID。 4、添加授权控制器 using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using TestWebApi.AuthCenter.Utility; namespace TestWebApi.AuthCenter.Controllers { [Route("api/[controller]")] [ApiController] public class AuthController : ControllerBase { //需要注入的服务 private readonly ILogger<AuthController> _logger; private readonly IConfiguration _configuration; private readonly IJwtService _jwtService; public AuthController(IConfiguration configuration, ILogger<AuthController> logger, IJwtService jwtService) { _configuration = configuration; _logger = logger; _jwtService = jwtService; } [Route("Login")] [HttpGet] public string Login(string username, string password) { var result = VerifyLogin(username, password); var token = result ? _jwtService.GetToken(username) : ""; return JsonConvert.SerializeObject(new { result, token }); } private bool VerifyLogin(string username, string password) { return "admin".Equals(username) && "123456".Equals(password); } } } 5、运行 (1) 运行Web API项目,在浏览器中输入https://localhost:5001/api/auth/Login,正常情况下会输出下面的内容: {"result":false,"token":""} (2) 在浏览器中输入https://localhost:5001/api/auth/Login?username=admin&password=123456,正常情况下会输出类似下面的内容: {"result":true,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJOaWNrTmFtZSI6Ik5ldENvcmUiLCJSb2xlIjoiQWRtaW5pc3RyYXRvciIsImV4cCI6MTYxMzk1OTM0NSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo5NTI3IiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo5NTI3In0.JdkUR3MV2uC8dQAnqzskFreVFdrHK4WTRrMJSDm7STY"}
|
请发表评论