在 Visual Studio 中使用 C# 实现 JWT(JSON Web Token)登录,通常分为两个部分:

  1. 后端(服务端):使用 ASP.NET Core Web API 生成 JWT Token(登录成功时颁发)
  2. 前端(客户端):使用 HttpClient 发送用户名密码,接收并保存 JWT,后续请求带上 Token

下面给你一个完整、可直接运行的 ASP.NET Core Web API 示例(.NET 8 推荐,也支持 .NET 6/7)

第一步:创建项目

打开 Visual Studio 2022/2025 → 创建新项目 → ASP.NET Core Web API → 选择 .NET 8(或 .NET 6)

第二步:安装 NuGet 包

在包管理器控制台运行:

Bash

Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
Install-Package System.IdentityModel.Tokens.Jwt

第三步:配置 appsettings.json

JSON

{
  "Jwt": {
    "Key": "你的超级复杂的密钥,至少32位,例如: MySuperSecretKey1234567890123456",
    "Issuer": "https://localhost:7253",
    "Audience": "https://localhost:7253",
    "ExpireMinutes": 60
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
}

第四步:创建登录模型和返回模型

C#

// Models/LoginModel.cs
public class LoginModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

// Models/TokenResponse.cs
public class TokenResponse
{
    public string Token { get; set; }
    public DateTime Expires { get; set; }
}

第五步:创建 JWT 服务

C#

// Services/JwtService.cs
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

public class JwtService
{
    private readonly string _key;
    private readonly string _issuer;
    private readonly string _audience;
    private readonly int _expireMinutes;

    public JwtService(IConfiguration configuration)
    {
        _key = configuration["Jwt:Key"];
        _issuer = configuration["Jwt:Issuer"];
        _audience = configuration["Jwt:Audience"];
        _expireMinutes = int.Parse(configuration["Jwt:ExpireMinutes"]);
    }

    public string GenerateToken(string username, string role = "User")
    {
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.Role, role),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: _issuer,
            audience: _audience,
            claims: claims,
            expires: DateTime.Now.AddMinutes(_expireMinutes),
            signingCredentials: creds);

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

第六步:创建登录控制器

C#

// Controllers/AuthController.cs
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
    private readonly JwtService _jwtService;

    // 模拟数据库用户(实际项目请换成 EF Core + 数据库 + 密码哈希)
    private readonly Dictionary<string, string> _users = new()
    {
        { "admin", "123456" },
        { "test", "888888" }
    };

    public AuthController(JwtService jwtService)
    {
        _jwtService = jwtService;
    }

    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginModel model)
    {
        if (string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.Password))
            return BadRequest("用户名或密码不能为空");

        if (_users.TryGetValue(model.Username, out var password) && password == model.Password)
        {
            var token = _jwtService.GenerateToken(model.Username, model.Username == "admin" ? "Admin" : "User");
            return Ok(new TokenResponse
            {
                Token = token,
                Expires = DateTime.Now.AddMinutes(60)
            });
        }

        return Unauthorized("用户名或密码错误");
    }
}

第七步:Program.cs 配置 JWT 认证(.NET 8 写法)

C#

var builder = WebApplication.CreateBuilder(args);

// 添加服务
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 注册 JwtService
builder.Services.AddSingleton<JwtService>();

// 添加 JWT 认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

var app = builder.Build();

// 配置管道
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();   // 一定要加这一行
app.UseAuthorization();

app.MapControllers();

app.Run();

第八步:测试登录(使用 Swagger 或 Postman)

POST 请求:https://localhost:7253/api/auth/login

请求体(JSON):

JSON

{
  "username": "admin",
  "password": "123456"
}

成功返回:

JSON

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6...",
  "expires": "2025-11-25T18:30:00Z"
}

第九步:保护其他接口(需要登录才能访问)

C#

[Authorize]  // 需要登录
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    [HttpGet("hello")]
    public IActionResult Hello()
    {
        var username = User.Identity.Name;
        return Ok($"Hello, {username}!你已成功使用JWT登录");
    }

    [HttpGet("admin")]
    [Authorize(Roles = "Admin")]  // 只有管理员能访问
    public IActionResult AdminOnly()
    {
        return Ok("这是管理员专属接口");
    }
}

前端 C# 客户端调用示例(控制台程序或 WinForm)

C#

var client = new HttpClient();
var loginData = new { username = "admin", password = "123456" };
var content = new StringContent(JsonSerializer.Serialize(loginData), Encoding.UTF8, "application/json");

var response = await client.PostAsync("https://localhost:7253/api/auth/login", content);
var json = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<TokenResponse>(json);

client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Bearer", result.Token);

var protectedResponse = await client.GetAsync("https://localhost:7253/api/test/hello");
Console.WriteLine(await protectedResponse.Content.ReadAsStringAsync());

这样就完整实现了基于 JWT 的登录认证系统。

更多推荐