.NET Core Web API key

后端 未结 2 2023
[愿得一人]
[愿得一人] 2020-12-29 05:26

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.

One thing I w

相关标签:
2条回答
  • 2020-12-29 05:29

    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/

    0 讨论(0)
  • 2020-12-29 05:33

    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/

    To summarise, in ASP.NET Core , you can use Middleware to control the http pipeline configuration. Middleware effectively replaces HttpHandlers, which were used in ealier versions of asp.net MVC.

    0 讨论(0)
提交回复
热议问题