0

I'm using the Angular Loopback SDK and am trying to implement a 401 handler that automatically detects when the user needs to authenticate. Loopback responds to a data request with a 401 and I use that to invoke a login dialog. Basically using the strategy described here -

http://docs.strongloop.com/display/public/LB/AngularJS+JavaScript+SDK#AngularJSJavaScriptSDK-Handling401Unauthorized

However, if the user supplies bad credentials then Loopback issues a 401 and that invokes the 401 handler again.... How best should I differentiate between a 401 which is a genuine AUTH failure and a failed login attempt?

MarkH
  • 682
  • 1
  • 6
  • 16

1 Answers1

0

Why is that bad?

You should be able to trigger your login dialog over and over again from the same state if the user doesn't know how to log in multiple times, right? If you are already showing the dialog, don't trigger it again and show an inline "Login failed" message. Or use a /login route and just intercept any 401 unauthorized and send to that page.

There is also an error message payload that you could inspect that might allow different messaging, so you could show a message "session expired" instead of just "you are logged out, please login." But in general, it's better to stay generic and just gently ask for a re-login.

You could also send different codes when the backend can determine that the username/email is on the system, but that's generally a security no-no and you'd have to override loopback defaults.

$httpProvider.interceptors.push(function($q, $location) {
  return {
    responseError: function(rejection) {
      if (rejection.status === 401) {

        $location.path('/login');

      }
      return $q.reject(rejection);
    }
  };
});
notbrain
  • 3,366
  • 2
  • 32
  • 42
  • It's bad because the sample code intercepts the 401 and caches the user's destination in $location.nextAfterLogin . When (if) the user credential fails then 401 is issued again with a target of /login, which is then promptly stored in the nextAfterLogin field - overwriting the original `$location.nextAfterLogin = $location.path(); $location.path('/login');` – MarkH Jun 22 '15 at 16:35
  • Stick the `$location.nextAfterLogin` value into a localStorage variable and add logic to skip overwriting it if it's '/login' and leave it to the original value. Clear it upon successful login. The built in auth mechanism isn't going to cover all possible states for you without some extra logic. – notbrain Jun 22 '15 at 17:21
  • That's what I did in the end. It's just a shame that the Loopback docs describe a 'solution' that cannot function in a very common scenario. – MarkH Jun 23 '15 at 08:57