在我们的接口调用中,都需要配置权限控制,下面介绍下在ASP NET CORE下使用JWT的步骤:
1.创建鉴权项目
由于鉴权并不需要每次调用都鉴权,所以我们可以自己创建一个项目工程作为鉴权中心,用户拿到鉴权后用对应信息去访问对应API;
2.引用对应DLL
引用System.IdentityModel.Tokens.Jwt.dll

3.编写JWT创建Token的代码
鉴权代码单独写在一个类里,为了应用也封装成接口,服务继承接口,一些信息写在了配置类里:首先贴出代码,如下:
接口信息:
public interface IJWTService { string GetToken(string UserName); }实现信息:
public class JWTService : IJWTService { private readonly IConfiguration _configuration; public JWTService(IConfiguration configuration) { _configuration = configuration; } public string GetToken(string UserName) { Claim[] claims = new[] { new Claim(ClaimTypes.Name, UserName), new Claim("NickName","Richard"), new Claim("Role","Administrator")//传递其他信息 }; SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"])); SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); /** * Claims (Payload) Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段,下面节选一些字段: iss: The issuer of the token,token 是给谁的 sub: The subject of the token,token 主题 exp: Expiration Time。 token 过期时间,Unix 时间戳格式 iat: Issued At。 token 创建时间, Unix 时间戳格式 jti: JWT ID。针对当前 token 的唯一标识 除了规定的字段外,可以包含其他任何 JSON 兼容的字段。 * */ var token = new JwtSecurityToken( issuer: _configuration["issuer"], audience: _configuration["audience"], claims: claims, expires: DateTime.Now.AddMinutes(10),//10分钟有效期 signingCredentials: creds); string returnToken = new JwtSecurityTokenHandler().WriteToken(token); return returnToken; } }
appsettings.json配置文件,红色部分是配置信息,如下:供上面代码获取配置信息
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "audience": "http://localhost:5000", "issuer": "http://localhost:5000", "SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"}
4.在鉴权项目工程Startup.cs文件里依赖注入JWT的服务类

编写获取Token的接口编码,如下:
[Route("api/[controller]")] [ApiController] public class AuthenticationController : ControllerBase { #region 构造函数 private ILogger<AuthenticationController> _logger = null; private IJWTService _iJWTService = null; private readonly IConfiguration _iConfiguration; public AuthenticationController(ILogger<AuthenticationController> logger, IConfiguration configuration , IJWTService service) { this._logger = logger; this._iConfiguration = configuration; this._iJWTService = service; }
No comments:
Post a Comment