python - 使用外部 Web 服务的 Django 身份验证

标签 python django authentication

我正在尝试使用 Django 身份验证,但使用外部 Web 服务调用。通过使用用户名和密码负载调用 Web 服务。 有没有任何教程或可能性可以做到这一点?我正在尝试使用远程用户,但它不起作用。我能够达到身份验证调用正常工作但仍停留在登录页面的程度

class AppRemoteUserBackend (RemoteUserBackend):

create_unknown_user = True

def authenticate (self, **credentials):
    //getting the user info by webservie call 
    customer = CustomerManagementService.getSelf(credentials)
    myUser= MyUser ()
    myUser.info= customer
    myUser.id = customer['id']
    myUser.username = credentials['username']
    t = myUser.is_authenticated()

    return myUser


from django.contrib.auth.models import User

class MyUser (User):



objects = None 

username = ""  
info= ""

def get_group_permissions (self):

    return [] 

def get_and_delete_messages (self):

    return []

最佳答案

如果您不想使用 REST API 框架,您可以通过这种方式处理基本的 HTTP 身份验证:

后端代码

import base64
from django.utils.encoding import smart_text, DjangoUnicodeDecodeError
from django.contrib.auth import authenticate

def basic_auth(http_request):

    if 'HTTP_AUTHORIZATION' in http_request.META:
        authdata = http_request.META['HTTP_AUTHORIZATION'].split()
        if len(authdata) == 2 and authdata[0].lower() == "basic":
            try:
                raw = authdata[1].encode('ascii')
                auth_parts = base64.b64decode(raw).split(b':')
            except:
                return
            try:
                uname, passwd = (smart_text(auth_parts[0]),
                                 smart_text(auth_parts[1]))
            except DjangoUnicodeDecodeError:
                return

            user = authenticate(username=uname, password=passwd)
            if user is not None and user.is_active:
                # We don't user auth.login(http_request, user) because
                # may be running without session
                http_request.user = user
                return True
    return

客户端代码

我个人使用请求,因为这样可以轻松地在有效负载中传递凭据:

import requests
from requests.auth import HTTPBasicAuth

auth = HTTPBasicAuth("some-username", "some-password")

res = requests.get("http://my-url", auth=auth)

关于python - 使用外部 Web 服务的 Django 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26896722/

相关文章:

python - 如何使用 Scikit-Learn 在 Python 中实现斐波那契数列?

python - 将不同长度的列表作为新列添加到数据框

这段代码中的 Python 优化?

python - 如何在Django中自动为注册到平台的新用户创建用户配置文件

authentication - 带有自定义 header 名称的 Swagger/OpenAPI Bearer 身份验证

java - Tomcat7安全样本如何调用login.jsp?

python - 混合 matplotlib 变换

python - Django:保存旧的查询集以供将来比较

Django 404 页面没有出现?

authentication - LSA 中 "Found no TGT' 的所有可能原因”