oauth2 Авторизация в Django Rest Framework с помощью django-auth-toolkit
Делаю oauth2 провайдер и клиент на, котором будут несколько защищенных для не авторизированных пользователей api эндпоинтов.
Я создал 2 django проекта:
На одном настроил django-oauth-toolkit чтобы он работал как провайдер, создал application
На втором сделал логику для получения токена, и один защищённый эндпоинт Теперь когда я пытаюсь использовать токен для авторизации в drf он пишет The access token is invalid.
вот настройки client проекта:
"""
Django settings for client_project project.
Generated by 'django-admin startproject' using Django 5.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""
from pathlib import Path
from loguru import logger
import sys
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-co_2e8=uoxw$qp=w$g&*4*3j=2w5dt1!&h@t^ib+lxt_!xtdmz'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'oauth2_provider',
'corsheaders',
'rest_framework',
"client_app",
]
MIDDLEWARE = [
'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',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
ROOT_URLCONF = 'client_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'client_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
'rest_framework.authentication.BasicAuthentication', # enables simple command line authentication
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
AUTHENTICATION_BACKENDS = [
'oauth2_provider.backends.OAuth2Backend',
'django.contrib.auth.backends.ModelBackend',
]
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ORIGIN_ALLOW_ALL = True
#superuser: root, root
#OAUTH2_CLIENT_ID = 'JK6JniqdmX8wq9237o9yUr8bvdP0t2S4eo4xXBIX' # public client
OAUTH2_CLIENT_ID = 'NxxMAmnxojRa2TudrDoKFN0IWARlenPoqSiHkByG' # confidentionl client
OAUTH2_CLIENT_SECRET = 'ageAK1kLM2q1oW95TMlUysYq7FOtF8GqW4q2euCkQwxfQOybIC0L5EndsC4aTuQxODeiWubLU1maUDbge91hEBmIEp4gdBeCl5WvrjHCV50ZjKxr0SLdwp4QgsCTJCkv'
OAUTH2_REDIRECT_URI = 'http://127.0.0.2:8000/oauth2/callback/'
OAUTH2_PROVIDER_URL = 'http://127.0.0.1:8000/o/'
Как мне правильно авторизироваться в drf с помощью моего токена полученного от провайдера