[Django]-User Authentication in Django Rest Framework + Angular.js web app

49👍

I imagine there are a lot of ways to do this, let me explain what I do, hopefully it is helpful. This is going to be a long post. I would love to hear how others do this, or better ways of implementing the same approach. You can also check out my seed project on Github, Angular-Django-Seed.

I use token authentication with Witold Szczerba’s http-auth-interceptor. The beauty of his approach is that whenever a request is sent from your site without proper credentials, you are redirected to the login screen, but your request is queued to be re-fired on login complete.

Here is a login directive used with the login form. It posts to Django’s auth token endpoint, sets a cookie with the response token, sets the default header with the token so all requests will be authenticated, and fires the http-auth-interceptor login event.

.directive('login', function ($http, $cookieStore, authService) {
return {
  restrict: 'A',
  link: function (scope, elem, attrs) {

    elem.bind('submit', function () {
      var user_data = {
            "username": scope.username,
            "password": scope.password,
      };

      $http.post(constants.serverAddress + "api-token-auth", user_data, {"Authorization": ""})
          .success(function(response) {
              $cookieStore.put('djangotoken', response.token);
              $http.defaults.headers.common['Authorization'] = 'Token ' + response.token;
              authService.loginConfirmed();
          });
    });
  }
}

})

I use the module .run method to set check for the cookie when a user comes to the site, if they have the cookie set I set the default authorization.

.run(function($rootScope) {
  $rootScope.$broadcast('event:initial-auth');
})

Here is my interceptor directive that handles the authService broadcasts. If login is required, I hide everything and show the login form. Otherwise hide the login form and show everything else.

.directive('authApplication', function ($cookieStore, $http) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {

          var login = elem.find('#login-holder');
          var main = elem.find('#main');

          scope.$on('event:auth-loginRequired', function () {
            main.hide();
            login.slideDown('fast');
          });

          scope.$on('event:auth-loginConfirmed', function () {
            main.show();
            login.slideUp('fast');
          });

          scope.$on('event:initial-auth', function () {
             if ($cookieStore.get('djangotoken')) {
               $http.defaults.headers.common['Authorization'] = 'Token ' + $cookieStore.get('djangotoken');
             }
             else {
               login.slideDown('fast');
               main.hide();
             }
          });
        }
     }
  })

To use it all my html was basically like this.

<body auth-application>
  <div id="login-holder">
    ... login form
  </div>

  <div id="main">
    ... ng-view, or the bulk of your html
  </div>

16👍

Check out django-rest-auth and angular-django-registration-auth also

https://github.com/Tivix/angular-django-registration-auth

https://github.com/Tivix/django-rest-auth

We’ve tried to solve most common Django auth/registration related things from a backend and angular perspective in these two libraries.

Thanks!

Leave a comment