Open johnnyAnd opened 1 month ago
I am using Django OAuth toolkit and the following code for OAuth implementation.
import requests from django.http import JsonResponse from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from .forms import AuthenticationForm, UserProfileForm from .models import UserProfile from oauth2_provider.models import get_application_model import base64 Application = get_application_model() def oauth_login(request): app = Application.objects.get(name="App") redirect_uri = request.POST.get("redirect_uri", "http://test.com:8002/redirect.html") authorization_url = ( f"http://test.com:8000/o/authorize/?client_id={app.client_id}&response_type=code&redirect_uri={redirect_uri}" ) return redirect(authorization_url) def oauth_callback(request): code = request.GET.get("code") if not code: return JsonResponse({'error': 'missing_code', 'details': 'Missing code parameter.'}, status=400) token_url = "http://test.com:8000/o/token/" client_id = Application.objects.get(name="App").client_id client_secret = Application.objects.get(name="App").client_secret redirect_uri = request.GET.get("redirect_uri", "http://test.com:8002/redirect.html") data = { "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri, "client_id": client_id, "client_secret": client_secret, } headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': f'Basic {base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()}', } response = requests.post(token_url, data=data, headers=headers) tokens = response.json() print(tokens) if response.status_code != 200: return JsonResponse({'error': 'token_exchange_failed', 'details': tokens}, status=response.status_code) request.session['access_token'] = tokens['access_token'] request.session['refresh_token'] = tokens['refresh_token'] return JsonResponse(tokens)
The issue is that it only works if the user is already logged in to the /admin site. I am not sure why is this behaviour. Can someone explain why I need to be in the Django Administration panel to enable the OAuth functionality?
@johnnyAnd you need to setup AUTHENTICATION_BACKENDS and MIDDLEWARE to make OAuth2 token authentications work. Please see https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_03.html
AUTHENTICATION_BACKENDS
MIDDLEWARE
I am using Django OAuth toolkit and the following code for OAuth implementation.
The issue is that it only works if the user is already logged in to the /admin site. I am not sure why is this behaviour. Can someone explain why I need to be in the Django Administration panel to enable the OAuth functionality?