简体   繁体   English

Django Rest Framework + Angular.js Web应用程序中的用户身份验证

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

I'm working on a webapp where users can login to see their online wine cellar. 我正在开发一个webapp,用户可以登录以查看他们的在线酒窖。

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模型设置,以及Angular中的前端设计,但我将这些部分放在一起很麻烦,我的主要问题是用户身份验证。

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?) 应该使用什么样的身份验证(令牌,会话,其他?)
  • 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. 根据我的理解,Angular在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 提前致谢

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 . 您还可以在Angular-Django-Seed的 Github上查看我的种子项目。

I use token authentication with Witold Szczerba's http-auth-interceptor . 我使用Witold Szczerba的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. 它发布到Django的身份验证令牌端点,使用响应令牌设置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. 我使用模块.run方法设置用户访问网站时检查cookie,如果他们有cookie设置我设置了默认授权。

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

Here is my interceptor directive that handles the authService broadcasts. 这是我的拦截器指令,它处理authService广播。 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. 要使用它我的所有HTML基本上都是这样的。

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

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

Check out django-rest-auth and angular-django-registration-auth also 查看django-rest-auth和angular-django-registration-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! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular.js中基于OpenID连接的身份验证与(drf oidc)Django休息框架后端 - OpenID connect based authentication in Angular.js with (drf oidc) Django rest framework backend 如何将对象ID从Angular.js传递到Django Rest Framework - How to pass object ID from Angular.js to Django Rest Framework 使用MongoEngine用户进行Django Rest Framework令牌认证 - Django Rest Framework Token Authentication with MongoEngine User Django rest 框架:创建用户请求身份验证 - Django rest framework : creating a user ask for authentication 使用 REST Framework Django 进行身份验证 - Authentication with REST Framework Django Django rest框架认证 - Django rest framework authentication django rest框架实现Angular js无限滚动 - angular js infinite scrolling with django rest framework 带有 JWT 用户身份验证的 Django Rest 框架(获取匿名用户) - Django Rest Framework With JWT user authentication (getting anonymous user ) 如何在 django rest 框架中使用 jwt 身份验证获取用户详细信息? - how to get the user details using jwt authentication in django rest framework? 将自定义用户身份验证添加到 django-rest-framework-simple-jwt - Adding custom user authentication to django-rest-framework-simple-jwt
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM