Mar 04 2024
public class ApiKeyMiddleware
{
private const string API_KEY_HEADER_NAME = "X-Api-Key";
private readonly RequestDelegate _next;
private readonly string _validApiKey;
public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
{
_next = next;
_validApiKey = configuration.GetValue<string>("ApiKey");
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue(API_KEY_HEADER_NAME, out var receivedApiKey) || receivedApiKey != _validApiKey)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync("Invalid or missing API Key.");
return;
}
await _next(context);
}
}
app.UseMiddleware<ApiKeyMiddleware>();
{
"ApiKey": "your-secret-api-key"
}
const apiKey = 'your-api-key-here'; // This should be securely stored and retrieved
const apiUrl = 'https://yourapi.com/data';
fetch(apiUrl, {
method: 'GET', // or 'POST', 'PUT', 'DELETE', etc., depending on the action
headers: {
'Content-Type': 'application/json',
'X-Api-Key': apiKey // Ensure this matches the header name expected by your API middleware
}
})
.then(response => {
if (response.ok) {
return response.json(); // Or `response.text()` if expecting a text response
}
throw new Error('Network response was not ok.');
})
.then(data => {
console.log(data); // Process your data here
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
Join 13,250+ subscribers to improve your .NET Knowledge.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.