[英].NET Core Web API key
I am developing an application that users can authenticate via username and password and we provide a JWT token that then gets validated on the server.我正在开发一个用户可以通过用户名和密码进行身份验证的应用程序,我们提供一个 JWT 令牌,然后在服务器上进行验证。
One thing I would like to add is the ability to have a special API Key (guid) that the users can use when integrating with this application instead of using a username and password.我想补充的一件事是能够拥有一个特殊的 API 密钥 (guid),用户在与此应用程序集成时可以使用它,而不是使用用户名和密码。
I am unsure how to do this since the authentication part seems to be a bit of a black box (using Aspnet Identity).我不确定如何执行此操作,因为身份验证部分似乎有点像一个黑匣子(使用 Aspnet Identity)。
Here is some of my code for the authentication setup.这是我用于身份验证设置的一些代码。
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,
});
//....
}
The above code works when having the [Authorized]
attributes on controllers and checking for the roles and such.上面的代码在控制器上具有
[Authorized]
属性并检查角色等时有效。
Anyone have any idea how I can pass some sort of Api-Key
header on all requests containing this special API Key for it to pass the [Authorized]
attributes?任何人都知道如何在包含此特殊 API 密钥的所有请求上传递某种
Api-Key
标头,以便它传递[Authorized]
属性? (The key is stored in the database.) (密钥存储在数据库中。)
This is what I did in the end:这就是我最后所做的:
public static void ApiKeyMiddlewear(this IApplicationBuilder app, IServiceProvider serviceProvider)
{
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments(new PathString("/api")))
{
// Let's check if this is an API Call
if (context.Request.Headers["ApiKey"].Any())
{
// validate the supplied API key
// Validate it
var headerKey = context.Request.Headers["ApiKey"].FirstOrDefault();
await ValidateApiKey(serviceProvider, context, next, headerKey);
}
else if (context.Request.Query.ContainsKey("apikey"))
{
if (context.Request.Query.TryGetValue("apikey", out var queryKey))
{
await ValidateApiKey(serviceProvider, context, next, queryKey);
}
}
else
{
await next();
}
}
else
{
await next();
}
});
}
private static async Task ValidateApiKey(IServiceProvider serviceProvider, HttpContext context, Func<Task> next, string key)
{
// validate it here
var valid = false;
if (!valid)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await context.Response.WriteAsync("Invalid API Key");
}
else
{
var identity = new GenericIdentity("API");
var principal = new GenericPrincipal(identity, new[] { "Admin", "ApiUser" });
context.User = principal;
await next();
}
}
This has changed quite a bit since I answered the original question (Answer is still valid).自从我回答了最初的问题(答案仍然有效)以来,情况发生了很大变化。 But you can read about this here: http://jamietech.com/2019/03/25/net-core-jwt-api-key/
但你可以在这里阅读: http : //jamietech.com/2019/03/25/net-core-jwt-api-key/
There is a nice article on using api keys in header requests on this link: http://www.mithunvp.com/write-custom-asp-net-core-middleware-web-api/在此链接上有一篇关于在标头请求中使用 api 密钥的好文章: http : //www.mithunvp.com/write-custom-asp-net-core-middleware-web-api/
To summarise, in ASP.NET Core , you can use Middleware to control the http pipeline configuration.总而言之,在 ASP.NET Core 中,您可以使用中间件来控制 http 管道配置。 Middleware effectively replaces HttpHandlers, which were used in ealier versions of asp.net MVC.
中间件有效地替代了 HttpHandlers,后者用于较早版本的 asp.net MVC。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.