在ASP.NET中,使用JWT(JSON Web Token)處理過期時間的方法如下:
安裝JWT庫:首先,你需要安裝一個JWT庫,例如System.IdentityModel.Tokens.Jwt
和Microsoft.IdentityModel.Tokens
。你可以使用NuGet包管理器來安裝這些庫。
配置Startup.cs:在Startup.cs
文件中,你需要配置Jwt驗證中間件。這里是一個示例配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = true;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
請確保將your_secret_key
替換為你自己的密鑰。
public string CreateJwtToken(Claim[] claims, int expirationMinutes = 60)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddMinutes(expirationMinutes),
SigningCredentials = creds
};
var token = new JwtSecurityToken(
issuer: "your_issuer",
audience: "your_audience",
claims: claims,
expires: DateTime.UtcNow.AddMinutes(expirationMinutes),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
[Authorize]
public class ApiController : ControllerBase
{
[HttpGet]
public async Task<IActionResult> Get()
{
var claims = HttpContext.User.Claims;
var token = HttpContext.User.Identity.AccessToken;
var validationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")),
ValidateIssuer = false,
ValidateAudience = false
};
var principal = await new JwtSecurityTokenHandler().ValidateTokenAsync(token, validationParameters, out SecurityToken validatedToken);
// 你可以在這里處理已驗證的用戶和令牌信息
}
}
在這個示例中,我們首先從HttpContext.User
獲取已驗證的用戶和訪問令牌。然后,我們創建一個TokenValidationParameters
對象,其中包含用于驗證令牌的參數。最后,我們使用JwtSecurityTokenHandler
的ValidateTokenAsync
方法驗證令牌。如果令牌有效,ValidateTokenAsync
方法將返回一個SecurityToken
對象,你可以從中獲取有關用戶的信息。