Django Rest框架中的用户身份验证+角。js web应用程序

时间:2022-03-11 11:50:49

I'm working on a webapp where users can login to see their online wine cellar.

我正在开发一个网络应用程序,用户可以登录它的在线酒窖。

I've got the Django REST models setup, as well as the front-end design in Angular but I'm having trouble putting the pieces together and my main issue is for user authentication.

我已经安装了Django REST模型,以及前端的角度设计,但是我在将各个部分组合在一起时遇到了麻烦,我的主要问题是用户身份验证。

I've read many posts on here and various tutorials but I can't seem to find a step by step method to implement authentication:

我在这里读过很多文章和各种教程,但是我似乎找不到一种循序渐进的方法来实现身份验证:

  • What kind of auth should be used (Token, Session, Other?)
  • 应该使用什么类型的auth(令牌、会话、其他?)
  • How is authentication managed on the server side (is it a view? a method in the UserModel or UserManager?)
  • 如何在服务器端管理身份验证(它是视图吗?UserModel或UserManager中的方法?
  • I have a custom User model (using email as username). Can I use the generic Django login method or do I need to create my own?
  • 我有一个自定义用户模型(以电子邮件作为用户名)。我可以使用一般的Django登录方法,还是需要创建自己的?
  • How is the authentication process managed between the server and client side?
  • 如何在服务器端和客户端之间管理身份验证过程?

From what I understand Angular makes a POST request on a url where DRF verifies that username and password match and returns a token or other auth proof.

根据我的理解,角在一个url上发出一个POST请求,其中DRF验证用户名和密码匹配,并返回一个令牌或其他身份验证。

I feel like I'm close but I need a more general view of how this works to put the pieces together.

我觉得我已经很接近了,但是我需要一个更全面的视角来看待这个问题。

Thanks in advance

谢谢提前

2 个解决方案

#1


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.

我想有很多方法可以做到这一点,让我解释一下我做了什么,希望这能有所帮助。这将是一个漫长的过程。我希望听到其他人是如何做到这一点的,或者更好地实现相同方法的方法。你也可以看看我在Github上的种子项目,angular - django种子。

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.

我在Witold Szczerba的http-auth-interceptor中使用令牌认证。他的方法的美妙之处在于,每当没有适当的凭证从您的站点发送请求时,您将被重定向到登录屏幕,但是您的请求将在登录完成时重新启动。

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.

下面是登录表单使用的登录指令。它将发送到Django的auth令牌端点,使用响应令牌设置cookie,使用令牌设置默认的标头,以便对所有请求进行身份验证,并触发http-auth-interceptor登录事件。

.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.

我使用module .run方法来设置当用户来到站点时对cookie的检查,如果他们有我设置的默认授权。

.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.

这是我的拦截器指令,它处理authService广播。如果需要登录,我将隐藏所有内容并显示登录表单。否则,隐藏登录表单并显示其他所有内容。

.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.

我的html基本上就是这样的。

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

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

#2


16  

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

也请查看django rest-auth和angular-django注册-auth

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

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

https://github.com/Tivix/django-rest-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.

我们试图从后端和角度的角度解决这两个库中最常见的Django auth/registration相关的问题。

Thanks!

谢谢!

#1


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.

我想有很多方法可以做到这一点,让我解释一下我做了什么,希望这能有所帮助。这将是一个漫长的过程。我希望听到其他人是如何做到这一点的,或者更好地实现相同方法的方法。你也可以看看我在Github上的种子项目,angular - django种子。

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.

我在Witold Szczerba的http-auth-interceptor中使用令牌认证。他的方法的美妙之处在于,每当没有适当的凭证从您的站点发送请求时,您将被重定向到登录屏幕,但是您的请求将在登录完成时重新启动。

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.

下面是登录表单使用的登录指令。它将发送到Django的auth令牌端点,使用响应令牌设置cookie,使用令牌设置默认的标头,以便对所有请求进行身份验证,并触发http-auth-interceptor登录事件。

.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.

我使用module .run方法来设置当用户来到站点时对cookie的检查,如果他们有我设置的默认授权。

.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.

这是我的拦截器指令,它处理authService广播。如果需要登录,我将隐藏所有内容并显示登录表单。否则,隐藏登录表单并显示其他所有内容。

.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.

我的html基本上就是这样的。

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

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

#2


16  

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

也请查看django rest-auth和angular-django注册-auth

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

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

https://github.com/Tivix/django-rest-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.

我们试图从后端和角度的角度解决这两个库中最常见的Django auth/registration相关的问题。

Thanks!

谢谢!