• Django-REST_Framework 第三方登录


    DRF第三方登录,我们将使用第三方包实现!!!

    1、首先安装

    pip install social-auth-app-django

    文档请看 https://python-social-auth.readthedocs.io/en/latest/configuration/django.html

    2、在setting文件中
    INSTALL_APP中加入

    'social_django',

    3、生成数据表
    由于第三方登录包已经生成好了migration的文件,所以我们只需migrate就好
    出现warning不需要在意。记得mysql引擎要使用innerdb。

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': "",
            'USER': '',
            'PASSWORD': "",
            'HOST': "127.0.0.1",
            #第三方登录。。。。不设置migration会出错
            'OPTIONS': {'init_command': 'SET default_storage_engine=INNODB;'}
        }
    }

    执行migrate之后,数据库会生成新的表用来记录第三方登录

    4、setting文件中
    设置邮箱和用户名和手机号均可登录

    # 设置邮箱和用户名和手机号均可登录
    AUTHENTICATION_BACKENDS = (
        'users.views.CustomBackend',
        #第三方登录配置之微博登录
        'social_core.backends.weibo.WeiboOAuth2',
        #第三方登录配置之QQ登录
        'social_core.backends.qq.QQOAuth2',
        #第三方登录配置之微信登录,微信有两种:oauth2 和 oauth2app,我们使用auth2
        'social_core.backends.weixin.WeixinOAuth2',
        'django.contrib.auth.backends.ModelBackend',
    )
    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',
                ],
            },
        },
    ]

    设置第三方登录的应用的key与secret
    需要自己去第三方平台创建应用,获取应用的key与secret

    # 第三方登录相关
    
    #微博应用的key与secret
    SOCIAL_AUTH_WEIBO_KEY = ''
    SOCIAL_AUTH_WEIBO_SECRET = ''
    
    #QQ应用的key与secret
    SOCIAL_AUTH_QQ_KEY = ''
    SOCIAL_AUTH_QQ_SECRET = ''
    
    #微信应用的key与secret
    SOCIAL_AUTH_WEIXIN_KEY = ''
    SOCIAL_AUTH_WEIXIN_SECRET = ''
    
    #配置用户授权之后重定向跳转的url
    SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/index/'

    5、url的配置

     # 首页
        path('index/', TemplateView.as_view(template_name='index.html'), name='index'),
        # 第三方登录
        path('', include('social_django.urls', namespace='social'))

    配置完成之后可以进行登录,但首页不会显示用户名
    drf登录获取的是cookie,所以需要更改social_core的源码使得它可以setcookie
    social_core/actions.py:

    from rest_framework_jwt.serializers import jwt_encode_handler,jwt_payload_handler
    
    def do_complete(backend, login, user=None, redirect_name='next',
                    *args, **kwargs):
        ......
            if backend.setting('SANITIZE_REDIRECTS', True):
            allowed_hosts = backend.setting('ALLOWED_REDIRECT_HOSTS', []) + 
                            [backend.strategy.request_host()]
            url = sanitize_redirect(allowed_hosts, url) or 
                  backend.setting('LOGIN_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

    原文:https://blog.csdn.net/qq_34374753/article/details/84501264

    博文纯属个人思考,若有错误欢迎指正!
  • 相关阅读:
    es6异步编程 Promise 讲解 --------各个优点缺点总结
    js重新讲解继承,es5的一些继承,es6继承的改变 ----------由浅入深
    node.js里的buffer常见操作,copy,concat等实例讲解
    node.js 写流 createWriteStream----由浅入深
    node.js 读取文件--createReadStream
    Java的位运算符—— 与(&)、非(~)、或(|)、异或(^)
    XML的特殊字符处理
    mysql语句收藏
    MYSQL学习
    利用HTML5 LocalStorage实现跨页面通信channel
  • 原文地址:https://www.cnblogs.com/yushenglin/p/10922966.html
Copyright © 2020-2023  润新知