Django+Vue打造购物网站(十一)

第三方登录

微博创建应用,修改回调地址
http://open.weibo.com/authentication

安装第三方登录插件
https://github.com/python-social-auth/social-app-django

pip install social-auth-app-django

INSTALL_APP中配置

'social_django',

生成表

python manage.py migrate

添加到AUTHENTICATION_BACKENDS
settings.py

# 设置邮箱和用户名和手机号均可登录
AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',
    'social_core.backends.weibo.WeiboOAuth2',
    'social_core.backends.qq.QQOAuth2',
    'social_core.backends.weixin.WeixinOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

配置context_processors

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        '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',
            ],
        },
    },
]

APP Secret和App key配置,settings里面

# 第三方登录,里面的值是你的开放平台对应的值
SOCIAL_AUTH_WEIBO_KEY = 'xxxxxxx'
SOCIAL_AUTH_WEIBO_SECRET = 'xxxxxx'

SOCIAL_AUTH_QQ_KEY = 'xxxxxxx'
SOCIAL_AUTH_QQ_SECRET = 'xxxxxxx'

SOCIAL_AUTH_WEIXIN_KEY = 'xxxxxxx'
SOCIAL_AUTH_WEIXIN_SECRET = 'xxxxxxx'
# 登录成功后跳转到首页
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/index/'

登录成功跳到首页,发现还处于未登录状态,我们需要对源码做修改
将social_core拷贝到extra_apps目录下
social_core/actions.py
原始代码

return backend.strategy.redirect(url)

修改为

# 修改源码适配drf
    response = backend.strategy.redirect(url)
    payload = jwt_payload_handler(user)
    response.set_cookie("name",user.name if user.name else user.username, max_age=24*3600)
    response.set_cookie("token", jwt_encode_handler(payload), max_age=24*3600)
    return response

现在就登录后就正常了。qq和微信的登录,一样的操作,只要去开放平台注册应用,其它跟微博登录一样设置就可以了

原文地址:https://www.cnblogs.com/gaoyongjian/p/9985926.html