0

I have some service that is going to send some messages to my endpoint. But I need to validate these messages by checking if the http header consist out of a fixed (for a period) api key and id. I can do this by check the header but I don't think this is good practice. Anybody a clue on how to verify that the message send from the service?

I have found something but it is for core2.2 and I need to use 2.1... (https://github.com/mihirdilip/aspnetcore-authentication-apiKey)

Thanks in advance

John
  • 602
  • 10
  • 27

3 Answers3

0

If you have quite a few endpoints, maybe even multiple controllers i would suggest writing a middleware to handle this.

But if this apikey check is only needed to one endpoint. Since you said "my endpoint". I would recommend just checking the header value in the controller action/endpoint

Example:

[HttpGet]
public async Task<IActionResult> ExampleEndpoint() {
   var headerValue = Request.Headers["Apikey"];
   if(headerValue.Any() == false)
    return BadRequest(); //401

   //your endpoint code
   return Ok(); //200
}
pontusv
  • 233
  • 1
  • 12
0

You can check the request header in custom middleware as shown here . Or you can use action filter to check the api key , see code sample here .

Nan Yu
  • 21,285
  • 5
  • 39
  • 110
0

Like I said I want to do this via the middleware and not in the end of the http pipeline. In the meantime I figured out a solution, it is a simple one but it works.

I created a class called MiddelWareKeyValidation with the following async method:

public async Task Invoke(HttpContext context)
        {
            if (!context.Request.Headers.Keys.Contains("X-GCS-Signature") || !context.Request.Headers.Keys.Contains("X-GCS-KeyId"))
            {
                context.Response.StatusCode = 400;      
                await context.Response.WriteAsync("User Key is missing");
                return;
            }
            else
            {
                var apiKey = new ApiKey { Signature = context.Request.Headers["X-GCS-Signature"], Key = context.Request.Headers["X-GCS-KeyId"] };

                if (!ContactsRepo.CheckValidUserKey(apiKey))
                {
                    context.Response.StatusCode = 401;
                    await context.Response.WriteAsync("Invalid User Key");
                    return;
                }
            }

            await _next.Invoke(context);
        }

Then I go to my Startup.cs in the Configure method where I add a new middleware like so:

app.UseMiddleware<MiddelWareKeyValidation>();

A good resource and credits goes to this article: https://www.mithunvp.com/write-custom-asp-net-core-middleware-web-api/

John
  • 602
  • 10
  • 27