我正在开发一个应用程序,用户可以通过用户名和密码进行身份验证,我们提供JWT令牌,然后在服务器上进行验证。
我想添加的一个功能是,允许用户在集成此应用程序时使用特殊的API密钥(GUID),而不是使用用户名和密码进行身份验证。
由于身份验证部分似乎有点黑盒子(使用Aspnet Identity),我不确定该如何实现这一点。
这里是我身份验证设置的一些代码。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<OmbiContext>(options =>
options.UseSqlite("Data Source=Ombi.db"));
services.AddIdentity<OmbiUser, IdentityRole>()
.AddEntityFrameworkStores<OmbiContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 1;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IMemoryCache cache)
{
var tokenOptions = (IOptions<TokenAuthentication>)app.ApplicationServices.GetService(
typeof(IOptions<TokenAuthentication>));
var ctx = (IOmbiContext)app.ApplicationServices.GetService(typeof(IOmbiContext));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.Value.SecretKey)),
RequireExpirationTime = true,
ValidateLifetime = true,
ValidAudience = "Ombi",
ValidIssuer = "Ombi",
ClockSkew = TimeSpan.Zero
};
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
Audience = "Ombi",
AutomaticAuthenticate = true,
TokenValidationParameters = tokenValidationParameters,
});
//....
}
当控制器上有[Authorized]
属性并检查角色等信息时,上述代码可以正常工作。
有人知道我如何在所有请求中传递某种Api-Key
头,包含此特殊API密钥以使其通过[Authorized]
属性?(密钥存储在数据库中。)