以下是一个基本的 .NET Core 3.1 JWT 示例:

首先,需要安装 Microsoft.AspNetCore.Authentication.JwtBearer 包:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

接下来,在 Startup.cs 文件中添加以下代码:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

// ...

public void ConfigureServices(IServiceCollection services)
{
    // ...

    // 添加 JWT 验证
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "your-issuer",
            ValidAudience = "your-audience",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
        };
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    app.UseAuthentication();
    app.UseAuthorization();

    // ...
}

在上面的代码中,我们使用 AddAuthentication() 方法添加了 JWT 验证,配置了默认的验证方案为 JwtBearerDefaults.AuthenticationScheme。然后,我们使用 AddJwtBearer() 方法配置了 JWT 验证选项,包括 issuer、audience、secret key 等。

接下来,在使用 JWT 的控制器中,我们可以使用 [Authorize] 特性来限制访问:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    [Authorize]
    public IEnumerable<WeatherForecast> Get()
    {
        // ...
    }
}

这将要求用户在访问 Get() 方法之前进行身份验证,如果未经身份验证,则会返回 401 错误。

接下来,我们可以使用以下代码来生成 JWT:

using System.IdentityModel.Tokens.Jwt;

// ...

var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("your-secret-key");
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new Claim[]
    {
        new Claim(ClaimTypes.Name, "your-username"),
        new Claim(ClaimTypes.Email, "your-email"),
        // ...
    }),
    Expires = DateTime.UtcNow.AddMinutes(30),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var encryptedToken = tokenHandler.WriteToken(token);

在上面的代码中,我们使用 JwtSecurityTokenHandler 类来生成 JWT。我们需要提供一个密钥、一些声明和一些其他选项,如过期时间等。最后,我们使用 WriteToken() 方法将 JWT 编码为字符串。

这就是 .NET Core 3.1 JWT 示例的基础知识。请注意,此示例仅用于演示目的,实际上应该更加严谨和安全。

net core 31 jwt 示例

原文地址: https://www.cveoy.top/t/topic/bGnW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录