How to use API keys to protected net APIs in ASP.Internet Core

There are several approaches to secure your APIs in ASP.Web Core 7. You can use a user authentication mechanism such as JWT tokens, ASP.Net Main Identification, bearer tokens, OpenID Hook up, or an OAuth 2. identification supplier, to identify a number of. API crucial authentication is but a further strategy you can adopt to help safe your APIs.

Note that API key authentication does not establish or authenticate the user. Instead, API important authentication utilizes API keys to authenticate the applications or providers that accessibility your APIs. An API vital is a token or exceptional identifier that is passed to an API through request header, cookie, or query string.

API keys can be made use of to management which purposes may possibly entry your API, keep track of their utilization styles, or limit which methods of your API they can use. Having said that, API keys are insufficient for protected authorization. For that, you would also need to have to implement person authentication.

In this post, we’ll look at how to implement API essential authentication in ASP.Web Core 7. To use the code illustrations furnished below, you must have Visual Studio 2022 mounted in your system. If you really don’t already have a copy, you can down load Visual Studio 2022 here.

Create an ASP.Net Main World-wide-web API job in Visible Studio 2022

Very first off, let’s make an ASP.Web Core 7 World wide web API undertaking in Visual Studio 2022. Comply with these techniques:

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new job.”
  3. In the “Create new project” window, find “ASP.Web Core Internet API” from the listing of templates shown.
  4. Simply click Following.
  5. In the “Configure your new project” window, specify the identify and spot for the new project.
  6. Optionally verify the “Place remedy and project in the exact same directory” check out box, based on your choices.
  7. Click on Subsequent.
  8. In the “Additional Information” window shown up coming, go away the “Use controllers (uncheck to use small APIs)” box checked, since we won’t be employing small APIs in this project. Go away the “Authentication Type” set to “None” (the default).
  9. Make certain that the check boxes “Enable Open API Assist,” “Configure for HTTPS,” and “Enable Docker” continue to be unchecked as we will not be applying those capabilities in this article.
  10. Simply click Create.

We’ll use this ASP.Net Main 7 World-wide-web API job to function with API vital authentication in the sections below.

Carry out API essential authentication utilizing middleware

Essentially, you can carry out API important authentication in ASP.Net Main in two diverse means: utilizing custom made characteristics or working with middleware. We’ll examine the two of these ways, beginning with middleware.

You can leverage middleware factors in ASP.Net Core to personalize how requests are processed and to examine, route, and alter messages as they traverse the ask for processing pipeline. In this article we’ll make a tailor made middleware to authenticate phone calls to our APIs.

Create a new .cs file named CustomApiKeyMiddleware in the Net API undertaking we developed previously. Your personalized middleware ought to have a constructor that accepts an argument of sort RequestDelegate as revealed in the code snippet specified beneath.

community class CustomApiKeyMiddleware

    non-public readonly RequestDelegate _next
    const string API_Critical = "Api_Vital"
    community CustomApiKeyMiddleware(RequestDelegate upcoming)
        _subsequent = upcoming

Because you are going to have to have to entry an instance of kind IConfiguration to read the Api_Crucial string from the AppSettings.json file, you need to move a reference of style IConfiguration as a parameter in the constructor as proven below.

general public course CustomApiKeyMiddleware

    personal readonly IConfiguration Configuration
    private readonly RequestDelegate _up coming
    const string API_Important = "Api_Essential"
    public CustomApiKeyMiddleware(RequestDelegate following, IConfiguration configuration)
        _future = following
        Configuration = configuration

Your customized middleware ought to evaluate the Api_Crucial browse from the AppSettings.json file with the 1 passed in the request header when invoking the endpoint. If the two match, the application grants entry to the endpoint, usually, an appropriate mistake messge is returned in the response.

The total resource code of the CustomApiKeyMiddleware class is specified under for reference:

community class CustomApiKeyMiddleware

    private readonly IConfiguration Configuration
    personal readonly RequestDelegate _next
    const string API_Important = "Api_Important"
    community CustomApiKeyMiddleware(RequestDelegate upcoming,
    IConfiguration configuration)
        _up coming = upcoming
        Configuration = configuration
    general public async Job Invoke(HttpContext httpContext)
        bool results = httpContext.Ask for.Headers.TryGetValue
        (API_Vital, out var apiKeyFromHttpHeader)
        if (!results)
            httpContext.Response.StatusCode = 401
            await httpContext.Response.WriteAsync("The Api Critical for
            accessing this endpoint is not out there")
        string api_vital_From_Configuration = Configuration[API_KEY]
        if (!api_key_From_Configuration.Equals(apiKeyFromHttpHeader))
            httpContext.Reaction.StatusCode = 401
            await httpContext.Response.WriteAsync("The authentication
            critical is incorrect : Unauthorized access")
        await _up coming(httpContext)

To use the middleware, you should really incorporate it to the request processing pipeline by which include the adhering to code in the Method.cs file.


Now, let us run the application and look through to the WeatherForecast endpoint in Postman. Take note that if you do not specify an Api_Critical string in your AppSettings.json file, you will see the correct message as proven in Determine 1 underneath.

api key authentication 01 IDG

Figure 1. Authentication fails because no Api_Essential benefit was passed in the ask for header.

When you pass the Api_Important benefit in the request header utilizing Postman, the endpoint will return data properly as shown in Determine 2.

api key authentication 02 IDG

Figure 2. The Api_Important benefit is handed effectively and the details is returned.

Employ API essential authentication employing tailor made attributes

Let us now examine how to put into practice API vital authentication applying personalized characteristics. An attribute is just like any other course that extends the System.Attribute course. Create a new .cs file named CustomApiKeyAttribute and enter the next code in there.

community course CustomApiKeyAttribute : Attribute, IAsyncActionFilter
    non-public const string API_Essential = "Api_Crucial"
    community async Process OnActionExecutionAsync
           (ActionExecutingContext context, ActionExecutionDelegate following)
        bool success = context.HttpContext.Request.Headers.TryGetValue
            (API_Crucial, out var apiKeyFromHttpHeader)
        if (!success)
            context.End result = new ContentResult()
                StatusCode = 401,
                Written content = "The Api Important for accessing this endpoint is not obtainable"
        IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
        IConfiguration Configuration = configurationBuilder.Make()
        string api_important_From_Configuration = Configuration[API_KEY]
        if (!api_crucial_From_Configuration.Equals(apiKeyFromHttpHeader))
            context.Final result = new ContentResult()
                StatusCode = 401,
                Content = "The Api key is incorrect : Unauthorized obtain"
        await upcoming()

You can now use the attribute on your controller class as demonstrated in the code snippet specified underneath.

community class WeatherForecastController : ControllerBase

    //Code omitted for brevity

Now, run the software yet again and specify a mistaken Api_Vital applying Postman. You need to see the ideal error information shown as revealed in Figure 3.

api key authentication 03 IDG

Determine 3. Passing an incorrect Api_Important value by using Postman will consequence in an unauthorized request and no details will be returned.


Notice that API crucial authentication is employed to validate the phone calls to our APIs, not the consumer. In other words, API keys are employed to authenticate the programs that mail requests to our APIs. API keys are beneficial for identifying the apps and products and services using your API, controlliing or restricting their obtain to your API methods, and monitoring their use patterns, but they can’t be employed to recognize unique people.

API crucial authentication has nothing to do with person authentication, i.e., validating the credentials of the user of the application earning the ask for. For truly protected authorization, you will have to use some type of person authentication mechanism.

Copyright © 2023 IDG Communications, Inc.