In a previous post, I mentioned sending OPTIONS responses so Swagger UIs can call a webservice without getting an error.
Unfortunately, there’s a second scenario where Swagger UI can conceal an error from being displayed because the error flow doesn’t include CORS headers.
The Problem Scenario
If your API Key doesn’t validate, then an error will be generated by the VerifyApiKey Policy and will return an error message to the Swagger UI browser without any CORS headers attached. This is what it looks like …
You’re in the browser and you ask for the Swagger UI to send a request with a bad API Key and you get back a “TypeError: Failed to fetch” message. And, when you look at the console you see No ‘Access-Control-Allow-Origin’ header is present.
When you switch over to the network view, you can see that the initial OPTIONS response came back successfully. But, you actually got a 401 Unauthorized response on your second request.
If you look further into the second request, you will find the error response’s headers don’t contain the Access-Control-Allow-Origin header.
If you then pull up the Trace tool in Apigee, you can see that the Verify API Key policy threw the error and the request returned before having any CORS headers applied to it.
How to Fix This
So, what we need to do is add CORS headers onto the response before it’s sent back. And, to do that we can use the Post-proxy Flow Hook. These are generally reserved to do logging tasks, but we are going to use them to add headers.
This Post flow will now add all of the headers on every response. So, the Apigee Trace tools output now looks like this:
Which will now send the CORS response headers to the browser:
And that will result in the real error message appearing in the Swagger UI Tester:
The Shared Flow used in the pictures above is some over done. Here is a much simpler Flow Task modeled after the previous post on the topic. This would be quick and easy to setup:
0 comments:
Post a Comment