Search code examples
asp.netauthenticationasp.net-web-apihateoas

Token Based Authentication For Automated Apps


(Using Web API) What is the correct/most appropriate way for automated apps to receive an error when their token expires, in order to get a new token?

I understand how token based authentication works for end users sitting in front of a screen, i.e. when their token expires, their next request will redirect them to a login page to get a new token.

However I was wondering what the best practice would be for automated apps. In this case, there is nothing sitting in front of the screen, so redirecting to a screen to hand key in details wouldn't be appropriate.

Should I return a url in the 401 response for the client app to pick up, so they know where to do a POST to get a new token, or is it more appropriate to just return a 401 and document where the user should go to get a new token?

If returning a url along with the 401 response is appropriate, what's the correct response format to achieve this?


Solution

  • Generally I think it's fine to just return a 401 and let the client deal with the error. At this point your web api app has done it's job and it's up to the client to decide what decision to make next. Presumably the client app should know where to get a new token, having created one in the first place.

    The other option is to have a 'Renew Token' method to generate a new token before the old one expires (if your tokens expire rather quickly, wouldn't bother otherwise).