This is a silly question but I dont know how to check to see, Im unsure how to pass my API key when making calls to the API I made in .Net 6 CWA
Im currently hosting the Web API on Heroku:
The Curl According to the UI looks like this:
curl -X 'GET' \
'https://chuckwarsapi.herokuapp.com/search?Query=luke' \
-H 'accept: */*' \
-H 'ApiKey: pgH7QzFHJx4w46fI~5Uzi4RvtTwlEXp'
I Am calling the API like this in my Component:
return this.httpClient.get(`https://chuckwarsapi.herokuapp.com/search?Query=${query}&ApiKey=${this.API_KEY}`);
I have built a Interceptor on my SPA but that hasnt helped as I still get
error
:
"Api Key was not provided"
The Way I added the API Key on the .Net was through some MiddleWare that checks to see if the API key is present
The middleware code:
private const string APIKEYNAME = "ApiKey";
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.HttpContext.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey))
{
context.Result = new ContentResult()
{
StatusCode = 401,
Content = "Api Key was not provided"
};
return;
}
var appSettings = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
var apiKey = appSettings.GetValue<string>(APIKEYNAME);
if (!apiKey.Equals(extractedApiKey))
{
context.Result = new ContentResult()
{
StatusCode = 401,
Content = "Api Key is not valid"
};
return;
}
await next();
}
I understand that the Api Key has to be referred to as ApiKey But im unsure how to pass it in the url. or how els to approach giving it the api key when I make the calls
here the Interceptor Code:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `ApiKey pgH7QzFHJx4w46fI~5Uzi4RvtTwlEXp`
}
});
return next.handle(request);
}
The Interceptor is being called in my module as such:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ApiInterceptorService, multi: true },
],
Appsettings.json in .net side:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ApiKey": "pgH7QzFHJx4w46fI~5Uzi4RvtTwlEXp"
}
CodePudding user response:
You should pass ApiKey
header in the request, instead of Authorization
header
request = request.clone({
setHeaders: {
ApiKey: `pgH7QzFHJx4w46fI~5Uzi4RvtTwlEXp`
}
});