social_django 集成第三方登录

1.将social_django添加到app配置中,settings.py
...
'social_django',
...

2.python manage.py migrate

3.第三方登录配置 settings.py

在配置文件中告知Django使用我们自定义的认证后端

AUTHENTICATION_BACKENDS = [
'social_core.backends.weibo.WeiboOAuth2', #微博
'social_core.backends.github.GithubOAuth2', # GitHub 登录后端
'django.contrib.auth.backends.ModelBackend', # 默认后台
]

社交登录秘钥设置

SOCIAL_AUTH_GITHUB_KEY = '' # 替换为 GitHub 提供的 Client ID
SOCIAL_AUTH_GITHUB_SECRET = '' # 替换为 GitHub 提供的 Client Secret

登陆后用户跳转的地址

SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'http://127.0.0.1:8000/'

4.配置settings.py
配置这里,当用户登录的时候,如果用户不存在,会自动在用户表中创建用户,并且关联用户信息。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
        ],
    },
},

]

5.最后配置路由
path('', include('social_django.urls',namespace='social')),
查看源码可以发现,里面已经包含了这些路由:urlpatterns = [
# authentication / association
path(f"login/str:backend", views.auth, name="begin"),
path(f"complete/str:backend", views.complete, name="complete"),
# disconnection
path(f"disconnect/str:backend", views.disconnect, name="disconnect"),
path(
f"disconnect/str:backend/int:association_id",
views.disconnect,
name="disconnect_individual",
),
]

6,发起登录请求
http://127.0.0.1:8000/login/github/

注意github的回调路由将其配置在Authorization callback URL里
http://127.0.0.1:8000/complete/github/。

posted @ 2024-11-15 15:03  林汉州win  阅读(27)  评论(0)    收藏  举报