text:
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:
- Launch the Visible Studio 2022 IDE.
- Click on on "Create new job."
- In the "Create new project" window, find "ASP.Web Core Internet API" from the listing of templates shown.
- Simply click Following.
- In the "Configure your new project" window, specify the identify and spot for the new project.
- Optionally verify the "Place remedy and project in the exact same directory" check out box, based on your choices.
- Click on Subsequent.
- 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).
- 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.
- 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") return 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") return 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.
When you pass the Api_Important benefit in the request header utilizing Postman, the endpoint will return data properly as shown in Determine 2.
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" return IConfigurationBuilder configurationBuilder = new ConfigurationBuilder() configurationBuilder.AddJsonFile("AppSettings.json") 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" return await upcoming() }
You can now use the attribute on your controller class as demonstrated in the code snippet specified underneath.
[CustomApiKey] [ApiController] [Route("[controller]")] 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.
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.