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

使用dj-rest-auth实现Google社交登录时遇TypeError问题求助

使用dj-rest-auth实现Google社交认证时遇到TypeError: string indices must be integers错误

问题详情

在通过dj-rest-auth对接Google社交认证时,调用/dj-rest-auth/google/接口返回以下错误:

TypeError at /dj-rest-auth/google/ string indices must be integers

预期行为是提交Google Access Token后,返回系统的认证密钥(JWT或Session Token),但目前流程被该错误阻断。

相关信息:

  • 配置截图:GOOGLE_CLIENT_ID和GOOGLE_SECRET_KEY配置
  • 请求截图:提交Google Access Token的请求
  • 错误截图:返回的错误信息

解决方案

1. 修正请求参数格式

从请求截图可以看到,你直接提交了纯文本的Access Token,但dj-rest-auth的Google认证接口要求参数必须是键值对格式:

  • 若用JSON请求,请求体应为:
{"access_token": "你的Google Access Token"}
  • 若用表单格式,需传递access_token=你的Token的键值对,同时设置请求头Content-Type: application/x-www-form-urlencoded。

这个错误的核心原因是接口期望解析一个包含access_token字段的对象,但收到了纯字符串,导致代码尝试用索引(类似data['access_token'])访问字符串时抛出异常。

2. 验证Google配置正确性

确保settings.py中的社交认证配置完整且正确:

INSTALLED_APPS = [
    # ...其他应用
    'rest_framework',
    'rest_framework.authtoken',
    'dj_rest_auth',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
]

SITE_ID = 1

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'APP': {
            'client_id': '你的GOOGLE_CLIENT_ID',
            'secret': '你的GOOGLE_SECRET_KEY',
            'key': ''
        },
        'SCOPE': ['profile', 'email'],
        'AUTH_PARAMS': {'access_type': 'online'}
    }
}

REST_USE_JWT = True

确认client_id和secret与Google Cloud Console中的凭据完全一致,无多余字符或空格。

3. 检查Access Token有效性

通过Google官方接口验证Token是否有效:

curl "https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=你的Access Token"

如果返回错误信息,说明Token已过期、权限不足或生成时的scope不匹配(需包含email和profile),需要重新获取。

4. 更新依赖版本

确保dj-rest-auth和django-allauth为兼容的稳定版本,避免版本冲突导致的异常:

pip install --upgrade dj-rest-auth django-allauth

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:07:34