因此,我一直在尝试以JWT分发的形式设置带有令牌身份验证的小型测试api,令牌分发部分按预期工作。
但是,由于我想让JWT服务的方法更通用,以允许对令牌进行不同类型的签名(因为我希望使用私钥/公钥对),所以我尝试在appsettings文件中设置更多选项然后决定了令牌生成的方式,我开始使用依赖注入来加载这些设置,直到现在我还没有接触过。
因此,当我想将那些设置为单例的配置类作为问题时,问题就来了(到目前为止,我通读的大多数指南都已经做到了,所以我认为这是正确的),并在他们在其中添加了ConfigureServices方法,因此我可以使用应该设置的参数,因为我通过获取appsettings文件的一部分在上面配置了几行。
但是,一旦我尝试访问它们,我什么也收不到,而是留下了空值。
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//the token config takes values from the appsettings.json file
var tokenConf = Configuration.GetSection("TokenConfiguration");
services.Configure<TokenConfiguration>(tokenConf);
//the signing credentials are assigned in the JwtTokenService constructor
var signingConf = new SigningConfiguration();
services.AddSingleton<SigningConfiguration>(signingConf);
//my token service
services.AddSingleton<IJwtTokenService, JwtTokenService>();
//i try to get hold of the actual values to use later on
var provider = services.BuildServiceProvider();
TokenConfiguration tc = provider.GetService<TokenConfiguration>();
SigningConfiguration sc = provider.GetService<SigningConfiguration>();
//i wanna use the values in here when i set the parameters for my authentication
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
return Task.CompletedTask;
}
};
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
//values used here since i specify issuer, audience and what kind of key to use in the settings
//the key & credentials differ based on a bool in the settings file and will either be a symmetric or asymmetric key
ValidIssuer = tc.Issuer,
ValidAudience = tc.Audience,
IssuerSigningKey = sc.Key
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
JwtTokenService.cs(IJwtTokenService仅具有在此处实现的CreateToken方法)
public class JwtTokenService : IJwtTokenService
{
private TokenConfiguration tokenConf;
public SigningConfiguration signingConf;
public JwtTokenService(IOptions<TokenConfiguration> tc) {
tokenConf = tc.Value;
signingConf = new SigningConfiguration();
//if the asymmetric bool is set to true, assign a new rsa keypair to the signing configuration
//otherwise, use a symmetric key with a hmac hash
if (tc.Value.AsymmetricKey)
{
using (var provider = new RSACryptoServiceProvider(2048))
{
signingConf.Key = new RsaSecurityKey(provider.ExportParameters(true));
}
signingConf.SigningCredentials =
new SigningCredentials(
signingConf.Key,
SecurityAlgorithms.RsaSha256);
}
else {
signingConf.Key =
new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(tc.Value.HmacSecret));
signingConf.SigningCredentials =
new SigningCredentials(
signingConf.Key,
SecurityAlgorithms.HmacSha512);
}
}
/// <summary>
/// Creates a token based on the running configuration
/// </summary>
public string CreateToken(List<Claim> claims)
{
var token = new JwtSecurityToken(
issuer: tokenConf.Issuer,
audience: tokenConf.Audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(tokenConf.Minutes),
signingCredentials: signingConf.SigningCredentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
TokenConfiguration.cs
public class TokenConfiguration
{
public string Audience { get; set; }
public string Issuer { get; set; }
public int Minutes { get; set; }
public bool AsymmetricKey { get; set; }
public string HmacSecret { get; set; }
}
SigningConfiguration.cs
public class SigningConfiguration
{
public SecurityKey Key { get; set; }
public SigningCredentials SigningCredentials { get; set; }
}
appsettings.json
"TokenConfiguration": {
"Audience": "ExampleAudience",
"Issuer": "ExampleIssuer",
"Minutes": 30,
"AsymmetricKey": true,
"HmacSecret": "example-secret-top-secret-secret-is_secret"
}
(在重要的情况下,该项目正在asp.net core 2.1中运行)
我是DI的新手,找不到很多用例与我的用例相同的示例,并且大多数此类情况涉及实际服务,而不是通过DI添加“配置”类。
也许有更好的方法可以做到这一点,而且我可能很愚蠢,因为他没有注意到或不知道谷歌究竟需要什么确切的东西才能找到正确的答案,所以很可能会在看/读一些关于DI的东西。此后不管。
任何输入或想法都会受到高度赞赏,因为我仍然对asp.net核心和整个流程还不陌生。
在我的情况下,关于私钥生成的一个小问题是,最好将生成的密钥对存储在密钥库中,或者将其存储在内存中,或者通过诸如openSSL之类生成它们并从中读取启动时是最好的选择吗?
答案 0 :(得分:1)
您正在从ServiceProvider请求TokenConfiguration
而不是IOptions<TokenConfiguration>
。
更改此行
TokenConfiguration tc = provider.GetService<TokenConfiguration>();
SigningConfiguration sc = provider.GetService<SigningConfiguration>();
与
IOptions<TokenConfiguration> tc = provider.GetService<IOptions<TokenConfiguration>>();
IOptions<SigningConfiguration> sc = provider.GetService<IOptions<SigningConfiguration>>();
然后使用tc.Value
访问选项。
在ServiceProvider
中需要的任何地方,我都不会直接从ConfigureServices
的配置中获取在Configuration["TokenConfiguration:Audience"]
中构建ConfigureServices
的好主意。