Jazure
Jazure

Reputation: 501

How to use Basic HTTP Django Authorization middleware?

I don't understand the django middleware snippet here: https://djangosnippets.org/snippets/1304/

I have incorporated the middleware correctly, and upon visiting my site, I can manually enter in the username and password and authenticate. My problem is that I don't know how to send a request from Postman/curl to authenticate. I have included an "Authorization" header in my Postman request, but I don't know how to format the values.

For example: "Authorization: user password"

    def __call__(self, request):
    if 'HTTP_AUTHORIZATION' not in request.META:
        return self._unauthed()
    else:
        authentication = request.META['HTTP_AUTHORIZATION']
        (auth_method, auth) = authentication.split(' ', 1)
        if 'basic' != auth_method.lower():
            return self._unauthed()
        auth = base64.b64decode(auth.strip()).decode('utf-8')
        username, password = auth.split(':', 1)
        if (
            username == settings.BASICAUTH_USERNAME and
            password == settings.BASICAUTH_PASSWORD
        ):
            return self.get_response(request)

        return self._unauthed()

Upvotes: 0

Views: 370

Answers (1)

Siyu
Siyu

Reputation: 12079

For curl, curl -H "Authorization: Basic $(echo -n admin:123456 | base64)" https://example.com/api/endpoint/

In Postman, there is an authorization tab under the url, you can basic auth as type and enter username and password, postman will base64 encode it and add to headers.

enter image description here

Upvotes: 1

Related Questions