How to add custom Header in Authlib on Django

342 Views Asked by At

I would need some of your help adapting Authlib with Django.

I'm trying to develop a Django app using OpenId and Authlib to connect my users and facing an issue with the access token, the issue invalid_client occurs. Using Postman I found out that the OpenId provider needs some parameters in the Header like 'Content-Length' or 'Host'.

When the Header param is defined in client.py, it works like a charm. However, I'd like to pass the custom header from views.py (mostly to avoid defining the Host directly in the package), but authorize_access_token doesn't allow multiple arguments,

def auth(request):
    token = oauth.customprovider.authorize_access_token(request)

Maybe the "Compliance Fix for non Standard" feature might help, but I wasn't able to adapt it for Django and the Header parameter https://docs.authlib.org/en/stable/client/oauth2.html#compliance-fix-oauth2

from authlib.common.urls import add_params_to_uri, url_decode

def _non_compliant_param_name(url, headers, data):
    params = {'site': 'stackoverflow'}
    url = add_params_to_uri(url, params)
    return url, headers, body

def _fix_token_response(resp):
    data = dict(url_decode(resp.text))
    data['token_type'] = 'Bearer'
    data['expires_in'] = int(data['expires'])
    resp.json = lambda: data
    return resp

session.register_compliance_hook(
    'protected_request', _non_compliant_param_name)
session.register_compliance_hook(
    'access_token_response', _fix_token_response)

Does anyone know a way to pass a custom Header to Authlib or defining it using the Compliance Fix and Django?

1

There are 1 best solutions below

0
On

I had to do this recently for a provider that required an Authorization header added to the the refresh token. Here is the code I used.

Add the register_compliance_hook inside the function that is called using the compliance_fix argument when initializing the service.

def _compliance_fixes(session):
    def _add_header_refresh(url, headers, body):

    headers.update({'Authorization': "Basic " + self.secret_client_key})

    return url, headers, body

    session.register_compliance_hook('refresh_token_request', _add_header_refresh)

oauth = OAuth()
oauth.register("oauth-service", compliance_fix=_compliance_fixes)