Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在django rest框架中使用django.contrib.auth?_Django_Angularjs_Authentication_Django Rest Framework - Fatal编程技术网

如何在django rest框架中使用django.contrib.auth?

如何在django rest框架中使用django.contrib.auth?,django,angularjs,authentication,django-rest-framework,Django,Angularjs,Authentication,Django Rest Framework,django rest框架使用django.contrib.auth进行身份验证和授权(如中所述) 然而,文档中没有提到如何使用rest框架对用户进行实际身份验证 默认情况下,django.contrib.auth视图将使用服务器端呈现的登录表单进行响应 但是,如果使用客户端框架(如AngularJs),则不需要这样做—您只需要一个api端点,可以对其进行身份验证 问题: 是否有我不知何故遗漏的django rest框架文档,解释了如何开箱即用地完成用户身份验证 有现成的解决方案吗 如果不是,

django rest框架
使用
django.contrib.auth
进行身份验证和授权(如中所述)

然而,文档中没有提到如何使用rest框架对用户进行实际身份验证

默认情况下,
django.contrib.auth
视图将使用服务器端呈现的登录表单进行响应

但是,如果使用客户端框架(如AngularJs),则不需要这样做—您只需要一个api端点,可以对其进行身份验证

问题:

  • 是否有我不知何故遗漏的
    django rest框架
    文档,解释了如何开箱即用地完成用户身份验证

  • 有现成的解决方案吗

  • 如果不是,建议采用什么方法来实现这一点,并尽量减少车轮的重新改造


假设您拥有登录视图:

注意:使用此方法,您必须确保SSL/TLS,因为用户名和密码以纯文本形式发送

import json
import requests

def login(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        login_url = 'http://your_url:port/rest-api/login/'
        response = requests.post(login_url, data={'username': username, 'password': password})
        response = json.loads(response.text)
        if response.status_code == 200:
            return render_to_response("login.html", {"success": True}, RequestContext(request))
您在rest api中的视图:

from django.contrib.auth.backends import ModelBackend as DjangoModelBackend

def login(request):
    response = base_response.copy()
    username = request.DATA.get('username', '')
    password = request.DATA.get('password', '')

    user = DjangoModelBackend().authenticate(username=email, password=password)
    if user is not None:
        response["message"] = "Authenticated"
    else:
        response["message"] = "Login Failed"

    return Response(response)
这是ModelBackend的一部分

from django.contrib.auth import get_user_model

class ModelBackend(object):

def authenticate(self, username=None, password=None, **kwargs):
    UserModel = get_user_model()
    if username is None:
        username = kwargs.get(UserModel.USERNAME_FIELD)
    try:
        user = UserModel._default_manager.get_by_natural_key(username)
        if user.check_password(password):
        return user
    except UserModel.DoesNotExist:
        return None

在API端点进行身份验证时,您通常不需要查看登录表单-您可以使用API令牌,也可以通过标头发送身份验证凭据,请参见如何执行此操作。

可能的重复项