一、JWT認證簡介
首先,JWT全稱為JSON Web Token,是一種輕量級的認證和授權方式,採用JSON格式傳遞信息,在HTTP請求頭中進行傳遞,通常被用來作為API的安全驗證方式。JWT由三部分組成:頭部、載荷和簽名。頭部存儲加密算法和令牌類型等信息,載荷包含了需要傳遞的用戶信息以及其他元數據,簽名用於驗證令牌的合法性。
二、安裝NuGet包
在Visual Studio中,我們可以通過NuGet包管理器來安裝JWT相關的依賴包。打開NuGet包管理器,搜索安裝Microsoft.AspNetCore.Authentication.JwtBearer包,這個包提供了JWT認證相關的操作和中間件。
// 安裝NuGet包 Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
三、JWT認證配置
接下來,我們需要在Startup.cs文件中,進行JWT認證的配置。在ConfigureServices方法中,添加JWT認證相關配置。
// 引入命名空間 using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; // JWT認證配置 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { // 驗證發行人 ValidateIssuer = true, ValidIssuer = Configuration["Jwt:Issuer"], // 驗證接收人 ValidateAudience = true, ValidAudience = Configuration["Jwt:Audience"], // 驗證令牌簽名 ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Secret"])) }; });
在上面的配置中,我們指定了驗證發行人、接收人和驗證令牌簽名所需的密鑰。需要注意的是,在實際應用中,請將密鑰保存在安全可靠的地方,避免泄露。
四、JWT令牌生成
在進行JWT認證時,需要先生成JWT令牌。我們可以在AuthenticationController.cs文件中,添加一個GenerateJwtToken方法來生成JWT令牌。
// 引入命名空間 using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; // 生成JWT令牌 [AllowAnonymous] [HttpPost] [Route("authenticate")] public ActionResult GenerateJwtToken([FromBody] User userParam) { // 驗證用戶信息 var user = _userService.Authenticate(userParam.Username, userParam.Password); if (user == null) return BadRequest(new { message = "賬號或密碼錯誤" }); // 生成令牌 var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_configuration["Jwt:Secret"]); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return Ok(new { Token = tokenString }); }
在上面的代碼中,我們首先驗證了用戶的賬號和密碼,然後按照JWT認證規範生成JWT令牌,並將令牌返回給客戶端。在生成令牌時,我們設置了過期時間和簽名規則等信息,以保證令牌的安全性。
五、使用JWT認證
在需要進行身份驗證的地方,我們可以使用AuthenticateAttribute來開啟JWT認證。
// 引入命名空間 using Microsoft.AspNetCore.Authorization; // 使用JWT認證 [Authorize] [HttpGet] [Route("user")] public ActionResult GetUser() { // 獲取當前用戶信息 var userId = User.Identity.Name; var user = _userService.GetById(int.Parse(userId)); return Ok(user); }
在上面的代碼中,我們在需要獲取用戶信息的地方,使用了AuthorizeAttribute來開啟JWT認證。只有在通過身份驗證之後,才可以調用該方法獲取用戶信息。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/270516.html