builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { 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")) // 密钥 }; });改为APPSETINGSC传入
时间: 2024-02-14 22:31:25 浏览: 151
c++ builder.4 组件详解
要将JWT认证配置从代码中移到appsettings.json文件中,可以按照以下步骤进行操作:
1. 在appsettings.json文件中添加JWT认证配置:
```json
{
"JwtSettings": {
"Issuer": "your_issuer",
"Audience": "your_audience",
"SecretKey": "your_secret_key"
}
}
```
2. 在Startup.cs文件的ConfigureServices方法中,注册并读取JWT认证配置:
```csharp
// 添加配置文件支持
var configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build();
// 读取JWT认证配置
var jwtSettings = configuration.GetSection("JwtSettings").Get<JwtSettings>();
// 添加JWT认证服务
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtSettings.Issuer,
ValidAudience = jwtSettings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))
};
});
// 注册JwtSettings配置
services.Configure<JwtSettings>(configuration.GetSection("JwtSettings"));
```
3. 创建一个JwtSettings类来存储JWT认证配置:
```csharp
public class JwtSettings
{
public string Issuer { get; set; }
public string Audience { get; set; }
public string SecretKey { get; set; }
}
```
这样,你就可以将JWT认证的配置从代码中移到appsettings.json文件中,并通过依赖注入的方式读取配置。确保将"your_issuer"、"your_audience"和"your_secret_key"替换为你的实际值。
阅读全文