You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Postman调用Django OAuth2接口时遇Invalid Client错误求助

问题:调用Django social convert-token接口返回invalid client错误

我在Postman中发起请求,使用从Facebook开发者平台获取的client_id、client_secret和token,调用本地Django服务的http://localhost:8000/api/social/convert-token接口,却出现invalid client错误。以下是相关信息:

请求信息

url:http://localhost:8000/api/social/convert-token?grant_type=convert_token&client_id=sdklhsjgvdshfuahhddkaj37637utydew7&client_secret=dgshjhsdfkgaskflj8363589klsskjnlksfjnljhfjmj83889ij&backend=facebook&token=lkdfjlkjhdsfkljhbdsncvkjdsh763uhkdjcbgjhxsgckjdsh7ytfgklfclkfoit76ejvmljfdlkjndsi736uihd

settings.py配置

from pathlib import Path

# 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/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'edk,wdjhshdajldkahsgca'

# 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',
    'coreapp',
    'cloudinary',
    'oauth2_provider',
    'social_django',
    'rest_framework_social_oauth2',
]

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',
]

ROOT_URLCONF = 'foodhub.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',
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

WSGI_APPLICATION = 'foodhub.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/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/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOGIN_REDIRECT_URL='/'
import cloudinary
import cloudinary.uploader
import cloudinary.api


#config heroku
import django_heroku
django_heroku.settings(locals())

#CSRF_TRUSTED_ORIGINS =['http://127.0.0.1:8000/restaurant/sign_up']

AUTHENTICATION_BACKENDS = (
   'social_core.backends.facebook.FacebookOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

# Facebook configuration
SOCIAL_AUTH_FACEBOOK_KEY = 'FACEBOOK_KEY'
SOCIAL_AUTH_FACEBOOK_SECRET = 'facebook_secret'

# Define SOCIAL_AUTH_FACEBOOK_SCOPE to get extra permissions from Facebook.
# Email is not sent by default, to get it, you must request the email permission.
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
    'fields': 'id, name, email,picture.type(large)'

urls.py配置

from re import template
from django.contrib import admin
from django.urls import path,include
from django.contrib.auth import views as auth_views
from django.contrib.auth import views
from coreapp import views 

urlpatterns = [
    #Web View - Admin
    path('admin/', admin.site.urls),
    path('', views.home,name='home'),
    
    #web View - Restaurant
    path('restaurant/sign_in/',auth_views.LoginView.as_view(template_name='restaurant/sign_in.html'),name='restaurant_sign_in'),
    path('restaurant/sign_out/',auth_views.LogoutView.as_view(next_page='/'),name='restaurant_sign_out'),
    path('restaurant/sign_up', views.restaurant_sign_up,name='restaurant_sign_up'),
     path('restaurant/', views.restaurant_home,name='restaurant_home'),
     
     #APIs
     # /convert-token (sing_in/sing_up) ,/revoke-token(sign-out)
    path('api/social/', include('rest_framework_social_oauth2.urls')),
    
]

解决方案

1. 区分OAuth2客户端与Facebook密钥

请求参数里的client_id和client_secret是Django OAuth Toolkit生成的应用凭证,不是Facebook开发者平台的密钥。操作步骤:

  • 若未创建管理员账号,运行python manage.py createsuperuser生成
  • 启动服务后访问http://localhost:8000/admin,进入Applications(oauth2_provider模块的应用)
  • 创建新应用:
    • 用户选择你的管理员账号
    • 客户端类型选Confidential
    • 授权类型勾选Resource owner password-based和Authorization code
    • 保存后复制生成的client_id和client_secret,替换请求中的对应参数

2. 替换Facebook配置占位符

settings.py中SOCIAL_AUTH_FACEBOOK_KEY和SOCIAL_AUTH_FACEBOOK_SECRET是占位符,需替换为Facebook开发者平台的真实密钥:

SOCIAL_AUTH_FACEBOOK_KEY = '你的Facebook App ID'
SOCIAL_AUTH_FACEBOOK_SECRET = '你的Facebook App Secret'

3. 修复settings.py语法错误

SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS字典未闭合,末尾添加}:

SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
    'fields': 'id, name, email,picture.type(large)'
}

4. 执行数据库迁移

确保oauth2_provider的表已创建,运行:

python manage.py migrate

完成以上步骤后重新发起请求,即可解决invalid client错误。

内容的提问来源于stack exchange,提问作者mick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:20:44