我正在尝试使用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 []
答案 0 :(得分:0)
如果您不想使用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)