JSON Web Token(JWT)是一種開放標準,用于在網絡之間安全地傳輸信息。JWT 可以用來身份驗證和授權。在 C# 中,你可以使用 JWT 來保護你的 Web API 或者其他需要安全訪問的資源。
以下是在 C# 中使用 JWT 的基本步驟:
dotnet add package System.IdentityModel.Tokens.Jwt
dotnet add package Microsoft.IdentityModel.Tokens
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace JwtExample
{
class Program
{
static void Main(string[] args)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
var signinCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, "user-id"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Role, "admin")
};
var jwtToken = new JwtSecurityToken(
issuer: "issuer",
audience: "audience",
claims: claims,
expires: DateTime.UtcNow.AddMinutes(30),
signingCredentials: signinCredentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(jwtToken);
Console.WriteLine($"Generated JWT: {tokenString}");
}
}
}
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace JwtExample
{
class Program
{
static void Main(string[] args)
{
var tokenString = "your-jwt-token";
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
var validationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "issuer",
ValidateAudience = true,
ValidAudience = "audience",
ValidateIssuerSigningKey = true,
IssuerSigningKey = key
};
try
{
var jwtTokenHandler = new JwtSecurityTokenHandler();
var principal = jwtTokenHandler.ValidateToken(tokenString, validationParameters, out _);
Console.WriteLine($"Token is valid. User ID: {principal.FindFirst(ClaimTypes.NameIdentifier)?.Value}");
}
catch (Exception ex)
{
Console.WriteLine($"Token is not valid: {ex.Message}");
}
}
}
}
首先,安裝 Microsoft.AspNetCore.Authentication.JwtBearer 包:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
然后,在 Startup.cs 文件中配置 JWT 身份驗證:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace JwtExample
{
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "issuer",
ValidateAudience = true,
ValidAudience = "audience",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
};
});
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
app.UseAuthorization();
// ...
}
}
}
現在,你可以在控制器中使用 [Authorize] 屬性來保護需要身份驗證的端點:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace JwtExample.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
[Authorize]
public string Get()
{
return "Hello, authorized user!";
}
}
}
這就是在 C# 中使用 JWT 的基本概述。你可以根據自己的需求進行調整和擴展。