When Unauthorized is forbidden
TL;DR: keep a copy of the HTTP spec nearby at all times.
We've been doing a lot of work recently on a shiny new self-service interface for getting your hands on an Atlas API key. As part of this, we've created new endpoints in Atlas 4.0 for performing administrative functions, such as creating and configuring API keys, which are used by an AngularJS front-end. One particularly gnarly thing came up regarding authorisation, and IE10, which is worthy of a mention.
Intercepting the unauthorized
You're able to authenticate using GitHub, Google or Twitter, and the OAuth tokens are passed through to the API as URI parameters. If the credentials were invalid or not present it responded with an HTTP code of 401, unauthorized, which seemed reasonable. On receiving a 401 response, an interceptor in the front-end then redirected to a login page. All was fine until we did some testing on IE10, where it refused point blank to redirect to the login page.
Debugging in the browser revealed that the 401 response from the server was actually being rewritten as a 404. Weird. A little head-scratching ensued but, after a quick read of the HTTP spec, I had a hunch. It states:
The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8)...
Ah, MUST include a WWW-Authenticate header. Given this is not HTTP authentication, we clearly weren't doing that. We switched the response to a 400 to see what would happen and, sure enough, it wasn't rewritten!
Bad request
As we were violating the spec with our 401 response, browser behaviour is obviously undefined so it's fair enough that IE rewrote the 401 as a 404. As the 400 isn't as descriptive, we've been careful to include error information in the body. If credentials are omitted you'll get:
{
"message": "Credentials are required",
"error_code": "NOT_AUTHENTICATED",
"error_id": "bdaecd9f-25ff-4301-a5e9-af3060c8e075"
}
If you'd like to get your mitts on a wealth of video and audio metadata, why not give the new, self-service, Atlas admin website a whirl and get yourself an API key? It even works in IE10 now.
This originally appeared on our company blog. Picture credit: Darwin Bell
blog comments powered by Disqus