Reputation: 4255
My question is rather theoretical than how to do it. I would like to know how the experts manage situation like I'm going to describe below.
I have a SPA using Angular and Breeze. The authentication is token based. I have an interceptor set up in Angular which takes care about that the requests contain the token, if the server returns 401 then the user will be redirected to the login page. Breeze uses the same $http instance as Angular.
When the app starts it fires 1-5 requests to the server and because the user is not authenticated, so that the request does not contain the token so the app gets 401 and the redirection will be fired. I'm planning that every user will be authenticated as Visitor who has very little grants, or Registered user where the user rights are managed.
My problem is that, when the first 401 result comes back, I don't know which one will arrive back first, the redirection will be fired, but the remaining results when coming back they throw errors in the console. I really don't like it and I don't like the method not paying attention to these exceptions.
For me it is obvious I need a request to the server to know whether the user is authenticated or not. I'm thinking about to make a request which will be fired as the very first. Until it comes back other requests to the server won't be fired. Due to that Angular's $http can't be set up to working synchronously I need a service which has a flag and until the flag is false other services can't make calls. But it seems a little bit clumsy solution.
The question is that how situations like this are handled? Do you have blogs dealing with situation like this?
Thanks for any help in advance!
Upvotes: 2
Views: 144
Reputation: 2599
When you set up your $http request, you can pass in an optional "config" object. This config object has a timeout property for which you can provide a promise. When this promise is resolved, your $http request will be aborted.
You can use this concept to "cancel" any outstanding $http requests when you receive the first 401 response back and then redirect the user to any authentication process you need.
I am about 80% of the way through finishing up a blog post on this very subject: http://jonnyknowsbest.co.uk/abort-cancelling-http-calls/
Upvotes: 0
Reputation: 42669
Well you can look at this Angular interceptor implementation and maybe use it https://github.com/witoldsz/angular-http-auth.
This interceptor has a retry mechanism when the initial requests fail due to 401 issue, once the user is authenticated.
Upvotes: 2