2

I am trying to use Django Authentication but with external web service calls. By calling a web service with a username and password payload. Is there any tutorial or possibility to do that? I am trying with the Remote User but it is not working. I am able to reach the point that authenticate call is working but still stuck with the login page

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 []

1 Answer 1

2

If you don't want to use a REST API framework, you can handle a basic HTTP authentication that way:

Backend code

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

Client code

I personnaly use Requests because it's easy to pass credentials in the payload that way:

import requests
from requests.auth import HTTPBasicAuth

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

res = requests.get("http://my-url", auth=auth)
Sign up to request clarification or add additional context in comments.

1 Comment

This isn't using an external authentication service, right? How can we use a service intended for single sign on?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.