您好,登錄后才能下訂單哦!
在C#中,我們可以使用ASP.NET Core框架來實現JWT(JSON Web Token)的刷新令牌功能。以下是一個簡單的示例,展示了如何在C#中間件中集成JWT刷新令牌:
首先,確保已經安裝了以下NuGet包:
在Startup.cs
文件中,配置JWT認證和授權:
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
public class Startup
{
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// 從appsettings.json文件中獲取JWT相關配置
var jwtSettings = Configuration.GetSection("JwtSettings");
var key = Encoding.ASCII.GetBytes(jwtSettings["SecretKey"]);
// 配置JWT認證
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
// 配置授權
services.AddAuthorization();
}
}
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
public class JwtService
{
private readonly IConfiguration _configuration;
public JwtService(IConfiguration configuration)
{
_configuration = configuration;
}
public string GenerateToken(string userId)
{
var jwtSettings = _configuration.GetSection("JwtSettings");
var key = Encoding.ASCII.GetBytes(jwtSettings["SecretKey"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, userId)
}),
Expires = DateTime.UtcNow.AddMinutes(60),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
public ClaimsPrincipal ValidateToken(string token)
{
try
{
var jwtSettings = _configuration.GetSection("JwtSettings");
var key = Encoding.ASCII.GetBytes(jwtSettings["SecretKey"]);
var validationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
var tokenHandler = new JwtSecurityTokenHandler();
var principal = tokenHandler.ValidateToken(token, validationParameters, out _);
return principal;
}
catch (Exception)
{
return null;
}
}
}
appsettings.json
文件中添加JWT相關配置:{
"JwtSettings": {
"SecretKey": "your_secret_key"
}
}
JwtService
生成和驗證JWT令牌。例如,在登錄成功后生成令牌并返回給客戶端:[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
// 驗證用戶名和密碼
var user = await _userService.Authenticate(request.Username, request.Password);
if (user == null)
{
return Unauthorized();
}
// 生成JWT令牌
var token = _jwtService.GenerateToken(user.Id);
return Ok(new { token });
}
[Authorize]
屬性,然后在操作方法中使用JwtService
驗證令牌。如果令牌有效,生成新的令牌并返回給客戶端。[HttpPost("refresh-token")]
[Authorize]
public IActionResult RefreshToken()
{
var token = Request.Headers["Authorization"].ToString().Split(' ')[1];
var principal = _jwtService.ValidateToken(token);
if (principal == null)
{
return Unauthorized();
}
var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var newToken = _jwtService.GenerateToken(userId);
return Ok(new { token = newToken });
}
這樣,你就可以在C#中間件中集成JWT刷新令牌功能了。請注意,這只是一個簡單的示例,實際項目中可能需要根據具體需求進行調整。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。