Hardy Erlinger - 233 - Sep 10, 2014

Authentication using the C# JsonServiceClient and its “OnAuthenticationRequired” hook works very well with a third party API that I need to use from my Xamarin client.

However, the API expires the WRAP authentication token after some time and when my client tries to access the API after the expiration date the calls naturally fail with a 401 response. Unfortunately, though, the API doesn’t send a “WWW-Authenticate” header back after the token has expired which in turn causes my “OnAuthenticationRequired” handler not to be called, resulting in all kinds of problems.

While the API doesn’t send a “WWW-Authenticate” header along with the 401 they do send a custom header “X-Authentication-Error” with a value of “TokenExpired”, so I do have something to go by which indicates to the client what happened.

In order to be able to respond to the token expiration and request a new one from the server I am looking for a hook somewhere in the C# service client which would allow me to respond to such a 401 response that contains a custom header. Unfortunately I was unable to find such a hook even after searching for several hours so any hints anyone could provide would be much appreciated. Thanks.

Hi Hardy, OnAuthenticated should still be fired for 401 Unauthorized responses even if there was no WWW-Authenticate header see: https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.Client/ServiceClientBase.cs#L497-L512

One way it wouldn’t get fired is if you didn’t have a Username/Password set on the Service Client?

Hardy Erlinger:

Thanks for your quick reply, Demis. User name and password are set so I don’t know what was happening there. Regardless, I implemented a different approach now where instead of relying on the auth token I store and use the auth cookies that are being sent with each API response. This seems to work fine and allows me to avoid the problem with the expiring auth token entirely.