在我們的接口調用中,都需要配置權限控制,下面介紹下在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; } #endregion [Route("Login")] [HttpGet] public string Login(string name, string password) { ///這里應該是需要去連接數據庫做數據校驗,為了方便所有用戶名和密碼寫死了 if ("sxwcorejwt".Equals(name) && "123456".Equals(password))//應該數據庫 { string token = this._iJWTService.GetToken(name); return JsonConvert.SerializeObject(new { result = true, token }); } else { return JsonConvert.SerializeObject(new { result = false, token = "" }); } } }
啟動鑒權項目服務,調用Login方法就可以獲取到鑒權的Token,如下圖;
5.API工程引用對應DLL
引用Microsoft.AspNetCore.Authentication.JwtBearer.dll
6.在API工程Startup.cs文件下添加配置代碼,
代碼配置幾乎都是一樣,有響應的備注,大家應該可以看懂,就不多說了,如下圖:
Startup.cs全部代碼如下:

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); #region JWT鑒權授權 //services.AddAuthentication();//禁用 var ValidAudience = this.Configuration["audience"]; var ValidIssuer = this.Configuration["issuer"]; var SecurityKey = this.Configuration["SecurityKey"]; services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //默認授權機制名稱; .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true,//是否驗證Issuer ValidateAudience = true,//是否驗證Audience ValidateLifetime = true,//是否驗證失效時間 ValidateIssuerSigningKey = true,//是否驗證SecurityKey ValidAudience = ValidAudience,//Audience ValidIssuer = ValidIssuer,//Issuer,這兩項和前面簽發jwt的設置一致 表示誰簽發的Token IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey))//拿到SecurityKey }; }); #endregion } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #region 通過中間件來支持鑒權授權 app.UseAuthentication(); #endregion app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
注意: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" }
7.在對應方法或者對應控制器上添加鑒權機制
如果是某一個方法需要鑒權只需要在對應方法上添加屬性:[Authorize],如下圖
如果是針對整個控制器上所有的方法都需要鑒權只需要在對控制器上添加屬性:[Authorize],方法就不需要添加了,如下圖
在控制器上添加屬性:[Authorize],會使所有此控制器的方法需要鑒權,但是如果此控制器個別方法不需要鑒權,可以在對應方法上添加:[AllowAnonymous],如下圖
8.測試鑒權
用postman測試如下:
沒有鑒權,報錯401,無鑒權,如下圖:
用步驟4獲取的Token有鑒權調用,如下圖:
至此NET CORE API權限控制之JWT的創建和引用已經完成,希望對你有幫助。
最后最后最后,重要的事情說三遍,來着是客,如果您覺得好就推薦或評論下,覺得不好希望能得到您的建議,繼續改善.