pythondjangoauthenticationoauthdjango-oauth

Django OAuth - Include Authorization Header in Middleware?


I configured django-oauth-toolkit successfully. I want to authorize third party users after receiving an access token from an OAuth Provider. I am able to access restricted websites with it using it like this after saving it in the Django Admin:

curl -H "Authorization: Bearer 123456" -X GET http://localhost:8000/secret/

The architecture I imagined was to have a login page where I can store the Authorization token in the headers using Django Sessions. However when I try to set the Authorization header in the middleware it is not letting me access the site. I inspected the response when I visited the site and it does not look like I'm saving the headers at all. I tried with the code below.

class OAuthDt:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        def process_request(request):
            request.META['Authorization'] = "Bearer 123456"
            return(request)
        request.Authorization = "Bearer 123456"
        request = process_request(request)
        response = self.get_response(request)
        return(response) 

Views.py

@login_required()
def secret_page(request, *args, **kwargs):
    return HttpResponse('Secret contents!', status=200)

So my guess is that either:

  1. The authentication check in my view is done before the Middleware saves the Header.
  2. There is something preventing me from updating the request headers or overwriting my header. Maybe another middleware

I am more inclined towards number 2 after checking the server logs.

[18/May/2020 13:54:38] "GET /secret/ HTTP/1.1" 302 0
This executes before redirecting user
Not Found: /accounts/login/
[18/May/2020 13:54:38] "GET /accounts/login/?next=/secret/ HTTP/1.1" 404 2362

This is the order of my middlewares:

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'DtTranslator.middleware.OAuthDt',
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
]

Any suggestions?


Solution

  • Well after checking the Oauth middleware I just had to modify the header properly.

    request.META['HTTP_AUTHORIZATION'] = "Bearer 123456"