我正在开发一个网络应用程序,用户可以在那里登录查看他们的在线酒窖。
我已经设置了Django REST模型,以及前端的角度设计,但是我很难将这些部件组合在一起,我的主要问题是用户身份验证。
我在这里阅读了许多文章和各种教程,但我似乎找不到一种逐步实现身份验证的方法:
据我所知,Angular在url上发出POST请求,其中DRF验证用户名和密码是否匹配,并返回令牌或其他验证。
我觉得我很接近,但我需要一个更全面的看法,这是如何把这些部分放在一起。
提前感谢
发布于 2013-12-10 16:56:56
我想有很多方法可以做到这一点,让我来解释一下我所做的,希望这是有帮助的。这将是一个很长的职位。我很想听听其他人是如何做到这一点的,或者更好地实施同样的方法。你也可以查看我的种子项目,在吉特布,角-姜戈-种子。
我使用Witold的http-auth-拦截器进行令牌身份验证。他的方法的美妙之处在于,每当在没有适当凭证的情况下从您的站点发送请求时,您将被重定向到登录屏幕,但您的请求在登录完成后将被重新触发。
以下是与登录表单一起使用的登录指令。它发布到Django的auth令牌端点,使用响应令牌设置cookie,设置带有令牌的默认标头,以便所有请求都经过身份验证,并触发http-auth-拦截器登录事件。
.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();
});
});
}
}
})
当用户访问站点时,我使用模块.run方法设置cookie检查,如果用户设置了cookie集,则设置默认授权。
.run(function($rootScope) {
$rootScope.$broadcast('event:initial-auth');
})
下面是我的拦截器指令,它处理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();
}
});
}
}
})
要使用它,我的html基本上是这样的。
<body auth-application>
<div id="login-holder">
... login form
</div>
<div id="main">
... ng-view, or the bulk of your html
</div>
发布于 2014-07-10 02:28:13
查看django-rest-auth和角-django-注册-auth
https://github.com/Tivix/angular-django-registration-auth
https://github.com/Tivix/django-rest-auth
我们尝试从后端和角度的角度解决这两个库中大多数与Django auth/注册相关的问题。
谢谢!
https://stackoverflow.com/questions/20498317
复制相似问题