[英].NET Core Web API key
我正在开发一个用户可以通过用户名和密码进行身份验证的应用程序,我们提供一个 JWT 令牌,然后在服务器上进行验证。
我想补充的一件事是能够拥有一个特殊的 API 密钥 (guid),用户在与此应用程序集成时可以使用它,而不是使用用户名和密码。
我不确定如何执行此操作,因为身份验证部分似乎有点像一个黑匣子(使用 Aspnet Identity)。
这是我用于身份验证设置的一些代码。
启动文件
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 密钥的所有请求上传递某种Api-Key
标头,以便它传递[Authorized]
属性? (密钥存储在数据库中。)
这就是我最后所做的:
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();
}
}
自从我回答了最初的问题(答案仍然有效)以来,情况发生了很大变化。 但你可以在这里阅读: http : //jamietech.com/2019/03/25/net-core-jwt-api-key/
在此链接上有一篇关于在标头请求中使用 api 密钥的好文章: http : //www.mithunvp.com/write-custom-asp-net-core-middleware-web-api/
总而言之,在 ASP.NET Core 中,您可以使用中间件来控制 http 管道配置。 中间件有效地替代了 HttpHandlers,后者用于较早版本的 asp.net MVC。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.