C#进行JWT身份验证

使用C#进行JWT身份验证的方法有很多,您可以根据您的项目需求选择合适的库或框架。

一种常见的方法是使用ASP.NET Core集成JWT,这样您可以利用Microsoft Identity Framework来存储用户和角色信息,并使用JWT来保护公开的REST API⁴。

具体的步骤如下:

  • 安装Microsoft.AspNetCore.Authentication.JwtBearer包

  • 在Startup.cs中配置服务和中间件,添加JwtBearer选项,指定密钥和验证参数

  • 在控制器中添加[Authorize]特性,以要求用户提供有效的Token才能访问API

  • 在登录控制器中生成Token,并返回给用户

以下是一个简单的示例代码:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    // 添加身份验证服务
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Jwt:Issuer"],
                ValidAudience = Configuration["Jwt:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
            };
        });

    // 其他服务...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 使用身份验证中间件
    app.UseAuthentication();

    // 其他中间件...
}

// LoginController.cs
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
    private IConfiguration _config;

    public LoginController(IConfiguration config)
    {
        _config = config;
    }

    [AllowAnonymous]
    [HttpPost]
    public IActionResult Login([FromBody]UserModel login)
    {
        IActionResult response = Unauthorized();
        var user = AuthenticateUser(login);

        if (user != null)
        {
            var tokenString = GenerateJSONWebToken(user);
            response = Ok(new { token = tokenString });
        }

        return response;
    }

     private string GenerateJSONWebToken(UserModel userInfo)
     {
         var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
         var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

         var token = new JwtSecurityToken(_config["Jwt:Issuer"],
           _config["Jwt:Audience"],
           null,
           expires: DateTime.Now.AddMinutes(120),
           signingCredentials: credentials);

         return new JwtSecurityTokenHandler().WriteToken(token);
     }

     private UserModel AuthenticateUser(UserModel login)
     {
         UserModel user = null;

         // 验证用户名和密码

         if (login.Username == "jarvan" && login.Password == "123456")
         {
             user = new UserModel { Username = "jarvan", EmailAddress = "[email protected]" };
         }
         return user;
     }
}

// WeatherForecastController.cs
[Authorize]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
   // ...
}

你可能感兴趣的:(ASP.Net,MVC,c#,asp.net)