title: How do I handle Token Authentication with AngularJS and Restangular?
body: <p>I have an angular app that uses <code>Restangular</code> and <code>ui.router.state</code>. </p>
  
  <h2>This is what I am currently doing</h2>
  
  <ol>
  <li><p>I have an Endpoint /Token that accepts a username/pass and gives
  back a bearer token and some user info.</p></li>
  <li><p>On successful login I save off the userinfo and token into a global var, user.current and I also set Restangular's default headers to include the bearer token:</p>
  
  <p>Restangular.setDefaultHeaders({Authorization: "Bearer " + data.access_token});</p></li>
  <li><p>When a user wants to access a route that has requiredAuth = true (set in the routeprovider as custom data like <a href="https://stackoverflow.com/questions/19862396/access-routeproviders-route-properties">Access routeProvider&#39;s route properties</a>) I check the user.current to see if its set.</p>
  
  <p>a. If user.current is set, take them to the route.</p>
  
  <p>b. If user.current is null or if the token would be expired (based on time) send them to /login</p></li>
  </ol>
  
  <h2>Problems/Concerns</h2>
  
  <ol>
  <li><p>If I <code>Ctrl+R</code> I lose my user info and the user has to log in again.</p>
  
  <p>a. Should I be saving off the bearer token or credentials into a cookie or something and have a user service try to grab that in the event that <code>user.current == null</code>?</p></li>
  <li><p>Am I even approaching this right?  Seems like something that literally 100% of people using AngularJS would want to do, yet, I can't find an example that aligns with my situation.  Seems like Angular would have mechanisms built in to handle some of this auth routing business...</p></li>
  <li><p>When do I need to be getting a new token/verifying the current one?  Do I just let anyone with devtools set something like <code>isAuthorized = true</code> so they can get to /admin/importantThings but then let the calls to /api/important things fail because they don't have a valid bearer token or should I be verifying that they have a valid token before I even let them get to that route?</p></li>
  </ol>