JSON WEB TOKEN
JWT是Json Web Token的縮寫,JWT, 是為了在網路應用環境間傳遞宣告而執行的一種基于JSON的開放標準(RFC 7519),該token被設計為緊湊且安全的,特別適用于分布式站點的單點登錄(SSO)場景,JWT的宣告一般被用來在身份提供者和服務提供者間傳遞被認證的用戶身份資訊,以便于從資源服務器獲取資源,也可以增加一些額外的其它業務邏輯所必須的宣告資訊,該token也可直接被用于認證,也可被加密,
安裝包參考
這里我們需要安裝兩個nuget包,所以在開始之前,請先通過nuget管理工具安裝:
- Microsoft.AspNetCore.Authentication.JwtBearer
- Swashbuckle.AspNetCore
Microsoft.AspNetCore.Authentication.JwtBearer這個用于做JWT Token的生成和認證,Swashbuckle.AspNetCore這個方便在開發環境呼叫調式API,
Add Authentication
接下來我們來添加JwtBearer認證,打開Startup.cs檔案,然后在ConfigureServices(IServiceCollection services)方法中添加以下代碼:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidIssuer = "Security:Tokens:Issuer", ValidateAudience = true, ValidAudience = "Security:Tokens:Audience", ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Security:Tokens:Key")) }; });
這樣系統就支持JWT認證了,接下來就可以在要使用認證的API中添加JWT認證了,在API上增加Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)即可:
[HttpGet("Get"), Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); }
生成JWT Token
現在GetAPI已經是需要認證才能呼叫了,所以我們需要生成一個JWT Token,并在呼叫API的時候帶上這個Token,這樣可以呼叫API了,
我們寫一個BuildToken的私有方法,該方法用于將用戶的ID生成為Token:
private string BuildToken(string userId) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes("Security:Tokens:Key"); var tokenDescriptor = new SecurityTokenDescriptor { Issuer = "Security:Tokens:Issuer", Audience = "Security:Tokens:Audience", Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userId) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); }
再寫一個API來回傳這個Token,在實際專案中,可以通過用戶名和密碼來確認用戶,確認成功后再回傳對應的Token,這里為了方便,就直接回傳admin用戶的Token:
[HttpGet("GetToken")] public IActionResult GetToken() { return Ok(new { Token = BuildToken("admin") }); }
使用Swagger呼叫API
API的JWT認證已經配置完成了,接下來我們來配置swagger,swagger可以很方便的呼叫API,
同樣打開Startup.cs檔案,并在ConfigureServices(IServiceCollection services)方法中添加以下代碼:
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI", Version = "v1" }); var securityScheme = new OpenApiSecurityScheme { Name = "JWT Authentication", Description = "Enter JWT Bearer token **_only_**", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", BearerFormat = "JWT", Reference = new OpenApiReference { Id = JwtBearerDefaults.AuthenticationScheme, Type = ReferenceType.SecurityScheme } }; c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { securityScheme, new string[] { } } }); });
然后在Configure(IApplicationBuilder app, IWebHostEnvironment env)方法中添加以下代碼:
app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI v1"));
這樣所有配置就完成了,運行專案進行測驗,
測驗API
我們先直接測驗一下GetAPI,點擊“Try it out”:

然后點擊"Execute":

API回傳了401,說明API現在不能呼叫成功,需要認證:

獲取Token
我們通過呼叫GetTokenAPI來獲取Token:

然后復制Token內容,注意不要復制整個結果,只要復制token的值就可以了:

然后點擊“Authorize”,粘貼剛剛復制的Token后再點擊Authorize就可以了,

我們再呼叫一次GetAPI試試,現在已經可以呼叫成功了:

完整源代碼:https://github.com/SeriaWei/JwtBearerWebAPI
原文地址:http://www.zkea.net/codesnippet/detail/dotnet-api-jwt-bearer.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/241167.html
標籤:.NET Core
