How to authenticate requests with django allauth (headless)
I am always getting a 401 response after login to django-allauth on session (and other endpoints). See example code:
def login(email, password):
response = requests.post(
f'{baseurl}/api/allauth/app/v1/auth/login',
headers={
'accept': 'application/json',
'Content-Type': 'application/json',
},
json={
'password': password,
'email': email
}
)
return response
def get_session(session_token):
response = requests.get(
f'{baseurl}/api/allauth/app/v1/auth/session',
headers={
'accept': 'application/json',
'Content-Type': 'application/json',
'X-Session-Token': session_token,
}
)
return response
login_response = login(email, password)
print(f"Status Code: {login_response.status_code}")
#print(f"Response: {json.dumps(login_response.json(), indent=2)}")
session_token = login_response.json()["meta"]["session_token"]
print("Session_token=",session_token)
session_response = get_session(session_token)
print(f"Status Code: {session_response.status_code}")
print(f"Response: {json.dumps(session_response.json(), indent=2)}")
Here is the output I am getting:
Status Code: 200
Session_token= 165aj7jqqq165drt6nbg8wo5dcf9ncch
Status Code: 401
Response: {
"status": 401,
"data": {
"flows": [
{
"id": "login"
},
{
"id": "signup"
},
{
"id": "password_reset_by_code",
"is_pending": false
}
]
},
"meta": {
"is_authenticated": false
}
}
So login works fine, but then calling other allauth headless endpoints always lead to 401 response. Calling other DRF endpoints protected by permission_classes = [permissions.IsAuthenticated] works just fine too.
Here are my important settings...
INSTALLED_APPS = [
...
"allauth",
"allauth.account",
"allauth.headless",
#'allauth.socialaccount',
# "allauth.mfa",
"allauth.usersessions",
"oauth2_provider",
...
"rest_framework",
...
]
AUTHENTICATION_BACKENDS = (
# Django
"django.contrib.auth.backends.ModelBackend",
# allauth
"allauth.account.auth_backends.AuthenticationBackend",
# oauth2
"oauth2_provider.backends.OAuth2Backend",
)
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"allauth.headless.contrib.rest_framework.authentication.XSessionTokenAuthentication",
"oauth2_provider.contrib.rest_framework.OAuth2Authentication", # oauth2
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.BasicAuthentication",
),
}
# ALLAUTH SETTINGS
ACCOUNT_LOGIN_METHODS = {"email"}
ACCOUNT_SIGNUP_FIELDS = ["email*", "password1*", "password2*"]
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
ACCOUNT_PASSWORD_RESET_BY_CODE_ENABLED = True
USERSESSIONS_TRACK_ACTIVITY = True
# HEADLESS_ONLY = True
HEADLESS_SERVE_SPECIFICATION = True
HEADLESS_CLIENTS = ("app",)
I have no idea what to change, but it looks like the X-Session-Token header is not used to authenticate the users in my requests...
Any idea of what could be wrong ?
Thanks in advance Loic