我使用django-tastypie
进行REST API,使用ApiKeyAuthentication
进行身份验证。我在CreateUserResource
中有一个api.py
用于创建新用户。现在,在所有教程中都指定无论何时完成任何GET或POST请求,都必须指定apikey
。但是客户如何收到此apikey
?
登录时,是否要对客户端进行身份验证并给出apikey
,当客户端注销时,该客户端将被撤销?
答案 0 :(得分:0)
在后端使用Tastypie在单页面应用程序中实现基本身份验证:
此类身份验证资源可能如下所示:
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from tastypie.http import HttpUnauthorized, HttpForbidden, HttpNotFound
from tastypie.authentication import ApiKeyAuthentication
from django.conf.urls import url
from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash
class AuthenticationResource(ModelResource):
def __get_api_key_for_user(self, user):
return '%s' % (user.api_key.key)
class Meta:
resource_name = 'authentication'
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/login%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('login'), name="api_login"),
]
def login(self, request, **kwargs):
self.method_check(request, allowed=['post'])
data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
last_login = user.last_login
login(request, user) // updates the last login
return self.create_response(request, {
'api_key': self.__get_api_key_for_user(user),
'last_login': last_login,
'username': username
})
else:
return self.create_response(request, {
'success': False,
'reason': 'disabled',
}, HttpForbidden )
else:
return self.create_response(request, {
'success': False,
'reason': 'Incorrect user name or password',
}, HttpUnauthorized )