I'm working on an API client for a REST service that uses a custom token-based authentiation scheme. The app hits a specificed authentication endpoint with a username and password, said endpoint returns a token that's good for X amount of time, and the app passes that token along with every subsequent request. When that token expires, we start over.
Most literature out there tells me to manually set the Authorization header on my request, but official Apple documentation discourages this, as that header is meant to be 'owned' by the built-in HTTP loading system. That said, official documentation on the 'correct' way to do this is shockingly lacking, and the standard didReceiveChallenge callbacks seem better suited for non-custom Basic/Digest/etc authentication schemes.
One thought I had was registering my own URLProtocol subclass to handle our custom flow. However, while I haven't had a chance to sit down and take a crack at that yet, my understanding from skimming these forums is that it's suffering from some bit-rot right now, so it 'might' (?) not be the best choice. That, and it's also not clear to me whether the rules around the Authorization header change when a custom URLProtocol is in play.
So, community (paging eskimo in particular!), what's the correct way for me to go about this?
It’s better to reply as a reply, rather than in the comments; see Quinn’s Top Ten DevForums Tips for this and other titbits.
if i am understanding this correctly, you're saying we should refrain from setting the bearer token manually like this?
Let me recap:
- In general, the
Authorizationheader is managed by the authentication challenge mechanism built-in toURLSession, which is why it’s listed in Reserved HTTP headers. - However, the built-in authentication challenge mechanism only supports Basic and Digest authentication challenges [1]. If you’re dealing with some other form of authentication challenge, your only option is to set the
Authorizationheader directly. This works, and given the number folks who’ve implemented OAuth this way, it’s likely to continue working.
The URLSession authentication challenge API is in desperate need of an overhaul. However, that’s been the case since I wrote this back in 2017:
that infrastructure does not support custom authentication challenges (r. 26855589)
so I’m not holding my breath )-:
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] There are other authentication challenges listed in <Foundation/NSURLProtectionSpace.h> but those apply to the connection, not to an individual request. And, yes, that includes NTLM.