The .NET core webservice has a feature called Middleware. You can use built-in middleware provided by Microsoft or create your own as well. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1 . The middleware is a series of steps the request goes through before/while hitting your actual endpoints, and allows you to stop the request should something go wrong.
Any official or custom middleware you use is added in the Configure() method of the Startup.cs object, for example "app.UseMiddleware<BasicAuthenticationMiddleware>();
" to use a custom one you've created or downloaded. We're using a custom-created middleware at my shop that does API key-based authentication. When your endpoint is hit for the running webservice, the HttpContext steps through each middleware's Invoke() method, where you can specify if the request should continue or fail. Here's an example:
/// <summary>
/// Handles basic authentication
/// </summary>
public class BasicAuthenticationMiddleware
{
private readonly RequestDelegate next;
// A collection of API keys for use with BasicAuthorization with API keys
private readonly IEnumerable<string> apiKeys;
public BasicAuthenticationMiddleware(RequestDelegate next, IEnumerable<string> apiKeys )
{
this.next = next;
this.apiKeys = apiKeys;
}
public async Task Invoke(HttpContext context)
{
string authorizationHeader = context.Request.Headers["Authorization"];
if (authorizationHeader == null || !authorizationHeader.StartsWith("Basic")
|| !BasicAuthentication.AuthenticateApiKey(authorizationHeader, apiKeys))
{
// authentication has failed, exit request and return a status code + headers
context.Response.Headers.Add("WWW-Authenticate", "Basic realm=\"realm\"");
context.Response.StatusCode = 401;
return;
}
// we're good to go - call the next Middlware's Invoke() method
await next.Invoke(context);
}
}
The order that the middleware runs in is the same order that you've specified them in the Configure() method of Startup.cs, so you'll likely want an error handling middleware first and then some authentication middleware to add security to the service.