在C#中,使用JWT(JSON Web Token)进行权限控制通常涉及以下几个步骤:
System.IdentityModel.Tokens.Jwt
或Microsoft.IdentityModel.Tokens
。你可以使用NuGet包管理器来安装这些库。Install-Package System.IdentityModel.Tokens.Jwt
或
Install-Package Microsoft.IdentityModel.Tokens
{
"JwtSettings": {
"Secret": "your-secret-key",
"Issuer": "your-issuer",
"Audience": "your-audience",
"SigningAlgorithm": "HS256"
}
}
public static class JwtUtil
{
private static readonly string _jwtSecret = Configuration["JwtSettings:Secret"];
private static readonly string _jwtIssuer = Configuration["JwtSettings:Issuer"];
private static readonly string _jwtAudience = Configuration["JwtSettings:Audience"];
public static string GenerateToken(Claim[] claims, int expirationMinutes = 30)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecret));
var signinCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var jwtToken = new JwtSecurityToken(
issuer: _jwtIssuer,
audience: _jwtAudience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(expirationMinutes),
signingCredentials: signinCredentials);
return new JwtSecurityTokenHandler().WriteToken(jwtToken);
}
public static ClaimsPrincipal ValidateToken(string token)
{
var validationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = _jwtIssuer,
ValidateAudience = true,
ValidAudience = _jwtAudience,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecret)),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
var principal = jwtSecurityTokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
return principal;
}
}
IEquatable<T>
接口以便于比较。public class User : IEquatable<User>
{
public int Id { get; set; }
public string Username { get; set; }
public string Role { get; set; }
// Implement IEquatable<User> methods
}
public class Role : IEquatable<Role>
{
public int Id { get; set; }
public string Name { get; set; }
// Implement IEquatable<Role> methods
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginModel model)
{
// Authenticate user and get user and role information
var user = new User { Id = 1, Username = model.Username, Role = model.Role };
// Generate JWT token
var claims = new[]
{
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Role, user.Role)
};
var token = JwtUtil.GenerateToken(claims);
return Ok(new { token });
}
[Authorize]
属性来保护方法。同时,确保在请求头中包含JWT令牌。[Authorize]
[HttpGet("protected-resource")]
public async Task<IActionResult> GetProtectedResource()
{
// Your logic to get protected resource
}
public class JwtAuthenticationFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var token = context.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
if (string.IsNullOrEmpty(token))
{
context.Result = new UnauthorizedResult();
return;
}
try
{
var claimsPrincipal = JwtUtil.ValidateToken(token);
var userId = claimsPrincipal.FindFirstValue(ClaimTypes.NameIdentifier);
var user = await _userService.GetUserByIdAsync(userId);
context.HttpContext.User = new ClaimsPrincipal(claimsPrincipal);
context.HttpContext.Items["user"] = user;
}
catch (Exception ex)
{
context.Result = new UnauthorizedResult();
}
await next();
}
}
Startup.cs
文件中注册JWT过滤器。public void ConfigureServices(IServiceCollection services)
{
// Register JWT filter
services.AddControllers(options =>
{
options.Filters.Add<JwtAuthenticationFilter>();
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Register JWT filter
app.UseMiddleware<JwtAuthenticationFilter>();
// Other middleware and routing configurations
}
通过以上步骤,你可以在C#中使用JWT实现权限控制。