温馨提示×

c# jwtbuilder怎样进行权限控制

c#
小樊
83
2024-12-12 21:34:12
栏目: 编程语言

在C#中,使用JWT(JSON Web Token)进行权限控制通常涉及以下几个步骤:

  1. 安装JWT库:首先,你需要安装一个JWT库,例如System.IdentityModel.Tokens.JwtMicrosoft.IdentityModel.Tokens。你可以使用NuGet包管理器来安装这些库。
Install-Package System.IdentityModel.Tokens.Jwt

Install-Package Microsoft.IdentityModel.Tokens
  1. 配置JWT:在应用程序中配置JWT密钥和签名算法。这些信息通常存储在appsettings.json文件中。
{
  "JwtSettings": {
    "Secret": "your-secret-key",
    "Issuer": "your-issuer",
    "Audience": "your-audience",
    "SigningAlgorithm": "HS256"
  }
}
  1. 创建JWT工具类:创建一个工具类来生成和验证JWT令牌。
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;
    }
}
  1. 创建用户和角色类:创建表示用户和角色的类,并实现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
}
  1. 在用户登录时生成JWT令牌:当用户登录成功时,根据用户的角色生成JWT令牌。
[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 });
}
  1. 在需要权限控制的控制器中使用JWT令牌:在需要权限控制的控制器中,使用[Authorize]属性来保护方法。同时,确保在请求头中包含JWT令牌。
[Authorize]
[HttpGet("protected-resource")]
public async Task<IActionResult> GetProtectedResource()
{
    // Your logic to get protected resource
}
  1. 验证JWT令牌:在全局过滤器或中间件中验证JWT令牌,以确保只有携带有效令牌的请求才能访问受保护的资源。
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();
    }
}
  1. 注册JWT过滤器:在应用程序的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实现权限控制。

0