Django 實現第三方帳號登陸網站

  這裏咱們使用 django-allauth 模塊來實現第三方帳號驗證登陸,官方文檔以下:https://django-allauth.readthedocs.io/en/latest/ 。html

 

安裝 django-allauthgit

pip install django-allauth

注意,django-allauth 須要在 Django1.10以上版本使用。github

 

在建好的項目 settings.py 文件中加入:數據庫

INSTALLED_APPS = ( ... # 須要的 app
    'django.contrib.auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', # 提供你想接入的第三方驗證帳戶,這裏以百度爲例
    'allauth.socialaccount.providers.baidu', ) SITE_ID = 1 LOGIN_REDIRECT_URL = '/'

除了 allauth.socialaccount.providers.baidu 外,也能夠把 baidu 換成 twitter 或 github 等幾十種不一樣的網站驗證,官方網站列出了全部支持的網站(https://django-allauth.readthedocs.io/en/latest/providers.htmldjango

不過國內的支持倒很少,有百度,微博,微信等。微信

 

在 urls.py 中加入一行app

re_path(r'^accounts/', include('allauth.urls')),

 

使用dom

./manage.py migrate

同步數據庫。ide

 

上述工做完成後,進入網站的後臺管理,就能夠看到下圖所示界面,多出了許多和網站驗證設置相關的數據表。測試

 

修改站點內容爲你網站的域名,我這裏測試用,直接是本地地址

 

 

在 Social Accounts › Social applications 下新增一個 Social applications

 

 

關於 Client id 和 Secret key 內容須要咱們到受權的第三方帳號網站開發者建立應用後拿到 對應的 id 和 key,這裏以百度爲例,登陸百度開發者中心,建立應用後咱們便拿到相應的 API Key(Client id)和 Secret Key 。

 

將 API Key 和 Secret Key 填入 Django 後臺的 Social applications 中。

添加受權回調頁地址 http://your domain/accounts/baidu/login/callback/ 

 

接下來咱們從新打開咱們的登陸界面,便有了百度的登陸連接

界面有點醜,這是 django-allauth 默認的登陸界面,咱們能夠在 project/templates/account 下建立 login.html 即可覆蓋 djano-allauth 的默認登陸模板,allauth自帶的模板放在 allauth/templates/account 下,也能夠在這裏替換。

 

登陸 -> 受權 -> 成功!

相關文章
相關標籤/搜索