在我們的介面呼叫中,都需要配置權限控制,下面介紹下在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(); }); } }View Code
注意: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的創建和參考已經完成,希望對你有幫助,
最后最后最后,重要的事情說三遍,來著是客,如果您覺得好就推薦或評論下,覺得不好希望能得到您的建議,繼續改善.

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/37615.html
標籤:.NET Core
