简体   繁体   English

.NET Core Web API 密钥

[英].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.

相关问题 .Net Core Web API - .Net Core Web API 具有外键关系的ASP.NET Core Web API和EF Core模型 - ASP.NET Core Web API & EF Core Models with Foreign Key relationship .NET CORE Web API 路由 - .NET CORE Web API Routing .NET 核心 Web API 身份验证和 .NET 身份 - .NET Core Web API Authentication and .NET Identity ASP.NET Core 2.1 Web.API更改应用程序见解的日志记录检测键 - ASP.NET Core 2.1 Web.API change application insights instrumentation key for logging 如何在 .NET Core Web API 中的字典键中将枚举转换为 int - How do I convert enum to int in Dictionary key in .NET Core Web API ASP.NET 核心 Web API - 实体类型'IdentityUserRole<long> ' 需要定义一个主键</long> - ASP.NET Core Web API - The entity type 'IdentityUserRole<long>' requires a primary key to be defined 如何将值作为字符串数组传递给 ASP.NET 核心 Web ZDB974238714CA8DE634A7CE1D08 中的 json 键 - How to pass value as string array to json key in ASP.NET Core Web API 如何在 ASP.NET Core 3.1 Web API 中将键值从结果转换为大写 - How to convert key value from result to uppercase in an ASP.NET Core 3.1 Web API 如何在 ASP.NET Core 6 Web API 中使用一对一关系将外键添加到表中? - How to add a foreign key into a table using one-to-one relationship in ASP.NET Core 6 Web API?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM