I am writing code for a Angular SPA (Single Page Application).
In back-end it connects to an engine written in
Javawhich does most of the processing(with which I am not concerned).I am using
UI Routerto do the routing.
Problem
However there is a tricky situation that I am not able to accomplish.
When logging in, I make a API call which returns a response in
JSONformat.If my call is successful(i.e. The login credentials match) I get a token in the returned
JSONwhich is basically just a string that is combination of symbols, alphabets and numbers.I am saving this in my
rootscopeand then accessing it as say $rootScope.myToken.I then use the same token in subsequent API calls.
Now what I want to do in AngularJS is to redirect a user to the Login Page if he/she is not logged in and tries to access some URL directly via entering it in address bar.
I found a fairly simple method here Redirect on all routes to login if not authenticated . However I am not able to implement this with my token.
Question
What should I do to make this work with the token? Any other suggestion apart from this answer is also welcome.
PS: I have tried multiple methods on stackoverflow and I found them either not working in my context or overly complicated for the purpose.
UPDATE: I could successfully implement Simon H's answer in my code. However the issue I am facing is, this will ONLY redirect as I want AFTER I have logged in and out of my application at least one. If I try to access a page directly via URL without logging in and out at least once, this method fails and I can still access the page. Any tips?