在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
对象,你可以从中获取有关用户的信息。