溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用django-allauth怎么實(shí)現(xiàn)第三方登錄

發(fā)布時(shí)間:2021-04-14 17:14:46 來(lái)源:億速云 閱讀:196 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)使用django-allauth怎么實(shí)現(xiàn)第三方登錄,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

本地登錄

先看看django-allauth的本地登錄如何配置。

安裝django-allauth

(env) > pip install django-allauth

修改配置文件:

my_blog/settings.py

...


TEMPLATES = [
  {
    ...
    'OPTIONS': {
      'context_processors': [
        # allauth 啟動(dòng)必須項(xiàng)
        'django.template.context_processors.request',
      ],
    },
  },
]


AUTHENTICATION_BACKENDS = (
  # Django 后臺(tái)可獨(dú)立于 allauth 登錄
  'django.contrib.auth.backends.ModelBackend',

  # 配置 allauth 獨(dú)有的認(rèn)證方法,如 email 登錄
  'allauth.account.auth_backends.AuthenticationBackend',
)


INSTALLED_APPS = [
  ...
  # allauth 啟動(dòng)必須項(xiàng)
  'django.contrib.auth',
  'django.contrib.messages',
  'django.contrib.sites',

  'allauth',
  'allauth.account',
  'allauth.socialaccount',
  
  # 可添加需要的第三方登錄
  'allauth.socialaccount.providers.github',
  'allauth.socialaccount.providers.weibo',
  ...
]

# 設(shè)置站點(diǎn)
SITE_ID = 1

# 登錄成功后重定向地址
LOGIN_REDIRECT_URL = '/article/article-list'

...

注意上面的配置中,有的內(nèi)容是創(chuàng)建項(xiàng)目時(shí)本來(lái)就有的,檢查一下你的項(xiàng)目中是否包含;有的內(nèi)容是完全新增的,不要漏掉了。

django-allauth也是一個(gè)app,因此需要分配給它url

my_blog/urls.py

...

urlpatterns = [
  ...
  path('accounts/', include('allauth.urls')),
  ...
]

最后一步是遷移數(shù)據(jù):

(env) > python manage.py migrate

這就完成了!

輸入django-allauth的默認(rèn)登錄頁(yè)面地址:

http://127.0.0.1:8000/accounts/login/

顯示頁(yè)面如下:

使用django-allauth怎么實(shí)現(xiàn)第三方登錄

設(shè)置網(wǎng)站首頁(yè)

教程到現(xiàn)在,我們的博客都還沒(méi)有分配首頁(yè)地址。

博客網(wǎng)站的首頁(yè)通常就是文章列表本身,因此把這個(gè)路由添加到my_blog/urls.py中:

my_blog/urls.py

...
from article.views import article_list

urlpatterns = [
  # home
  path('', article_list, name='home'),
  ...
]
...

再把登錄成功后的重定向地址改過(guò)來(lái):

my_blog/settings.py

...
# 重定向 url
#LOGIN_REDIRECT_URL = '/article/article-list'
LOGIN_REDIRECT_URL = '/'

這樣就擁有地址為http://127.0.0.1:8000首頁(yè)啦。

美化模板

django-allauth自帶的模板是簡(jiǎn)陋的,需要覆寫為自己網(wǎng)站的風(fēng)格才能使用。

還記得我們一直在使用的虛擬環(huán)境嗎?沒(méi)錯(cuò),所有項(xiàng)目運(yùn)行所需的第三方庫(kù)都是保存在虛擬環(huán)境的文件夾中的,在本教程中也就是env文件夾了。找到下面的路徑:

env\Lib\site-packages\allauth\templates\account\login.html

這個(gè)login.html就是原始的登錄模板文件了。雖然可以直接修改這個(gè)文件來(lái)優(yōu)化頁(yè)面,但是這樣做是很蠢的,因?yàn)槊慨?dāng)你升級(jí)庫(kù)、或者換臺(tái)電腦部署時(shí),模板又恢復(fù)回去了。

正確的做法是復(fù)制這個(gè)login.html到你自己項(xiàng)目的templates文件夾中去。即你需要在項(xiàng)目中創(chuàng)建一個(gè)完全相同的路徑:

templates\account\login.html

Django會(huì)優(yōu)先在項(xiàng)目中尋找模板文件,因此只要相對(duì)路徑相同,則可以達(dá)到覆寫的目的。

接下來(lái)就可以愉快的定制風(fēng)格了。

參考代碼如下:

templates\account\login.html


{% extends "base.html" %}
{% load i18n %}
{% load account socialaccount %}
{% block title %}登錄{% endblock %}

{% block content %}
<div class="container">
  <div class="row">
    <div class="col-12">
      <br>
      {% get_providers as socialaccount_providers %}
      {% if socialaccount_providers %}
      <p>
        {% blocktrans with site.name as site_name %}請(qǐng)登錄已有本地賬號(hào)或<a href="{{ signup_url }}">注冊(cè)</a>新賬號(hào)。
        也可以通過(guò)第三方登錄:{% endblocktrans %}
      </p>

      <div class="socialaccount_ballot">
        <h6 class="mb-2 mt-4">第三方登錄:</h6>
        <ul class="socialaccount_providers">
         {% include "socialaccount/snippets/provider_list.html" with process="login" %}
        </ul>
        <h6 class="mb-2 mt-4">本地登錄:</h6>
      </div>

      {% include "socialaccount/snippets/login_extra.html" %}

      {% else %}
      <p>{% blocktrans %}If you have not created an account yet, then please
      <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %}</p>
      {% endif %}
      <div class="col-6">
        <form class="login" id="login_form" method="POST" action="{% url 'account_login' %}">
          {% csrf_token %}
          <div class="form-group">
            <label for="id_login">賬號(hào): </label>
            <input type="text" name="login" placeholder="請(qǐng)輸入用戶名或Email" autofocus="autofocus" required
              id="id_login" class="form-control" />
            <small class="form-text text-muted ml-1">
              還沒(méi)有賬號(hào)?
              <a href="{% url 'account_signup' %}" >
                注冊(cè)新賬號(hào)
              </a>
            </small>
          </div>
          <div class="form-group mb-1">
            <label for="id_password">
              密碼:
            </label>
            <input type="password" name="password" placeholder="請(qǐng)輸入密碼" required id="id_password"
              class="form-control" />
            <small class="form-text text-muted ml-1">
              <a class="secondaryAction layui-text" href="{% url 'account_reset_password' %}">
                忘記密碼?
              </a>
            </small>
          </div>
          <div class="custom-control custom-checkbox mb-2">
            <input type="checkbox" name="remember" id="id_remember" checked class="custom-control-input" />
            <label for="id_remember" class="custom-control-label">
              保持登錄
            </label>
          </div>
          <button class="primaryAction btn btn-primary" type="submit" hidden id="submit_login">確認(rèn)</button>
          <button class="primaryAction btn btn-primary" type="button" id="on_submit_login">確認(rèn)</button>
        </form>
      </div>
    </div>
  </div>
</div>
{% endblock %}

實(shí)際效果如下:

使用django-allauth怎么實(shí)現(xiàn)第三方登錄

除了登錄頁(yè)面以外,其他的所有頁(yè)面,如注冊(cè)、郵箱認(rèn)證頁(yè)面及郵件、第三方登錄頁(yè)面等都可以用這種方法進(jìn)行覆寫。教程中就不再贅述,讀者請(qǐng)自行嘗試。

注冊(cè)

接下來(lái)看看注冊(cè)頁(yè)面。

點(diǎn)擊注冊(cè)按鈕,則看到如下頁(yè)面:

使用django-allauth怎么實(shí)現(xiàn)第三方登錄

需要注意的是郵箱這一項(xiàng)如果你填了,那么站點(diǎn)會(huì)自動(dòng)向填寫的郵箱發(fā)送認(rèn)證郵件。因此前面章節(jié)中講過(guò)的關(guān)于郵箱的配置一定要正確,否則就會(huì)得到一個(gè)ConnectionRefusedError的錯(cuò)誤。相關(guān)的配置項(xiàng)如下:

my_blog/settings.py

# SMTP服務(wù)器
EMAIL_HOST = 'your smtp'
# 郵箱名
EMAIL_HOST_USER = 'your email'
# 郵箱密碼
EMAIL_HOST_PASSWORD = 'your password'
# 發(fā)送郵件的端口
EMAIL_PORT = 25
# 是否使用 TLS
EMAIL_USE_TLS = True
# 默認(rèn)的發(fā)件人
DEFAULT_FROM_EMAIL = 'your email'

記得修改為你自己的郵箱配置。

另外需要注意的是django-allauth所注冊(cè)的賬號(hào)與django內(nèi)置的本地賬號(hào)是通用的,也就是說(shuō)通過(guò)內(nèi)置User創(chuàng)建的賬號(hào),是可以通過(guò)django-allauth登錄的。

有了django-allauth,之前教程中寫的用戶登錄、注冊(cè)以及密碼重置模塊統(tǒng)統(tǒng)都可以不要了。那既然如此,博主繞了這么大個(gè)彎不是坑人嗎?這個(gè)嘛,學(xué)習(xí)就是要變著法折騰..

GitHub登錄

搞定了本地登錄,接下來(lái)的第三方登錄才是重點(diǎn)。

由于GitHub的第三方登錄是最容易的,因此作為例子來(lái)講解。

作為合格的程序員,怎么能沒(méi)有GitHub賬號(hào)!

GitHub注冊(cè)O(shè)Auth

創(chuàng)建第三方登錄的第一步,是需要在GitHub網(wǎng)站上創(chuàng)建OAuth應(yīng)用。登錄GitHub賬號(hào),然后進(jìn)入地址:

https://github.com/settings/applications/new

不排除以后這個(gè)地址會(huì)變,如果不對(duì)就麻煩讀者在個(gè)人主頁(yè)的settings里找一找OAuth的設(shè)置了。

進(jìn)入頁(yè)面后,填寫一下內(nèi)容:

使用django-allauth怎么實(shí)現(xiàn)第三方登錄

填寫的是本地IP,以后部署在線上再修改成實(shí)際的域名。

注意callback URL填寫的內(nèi)容。點(diǎn)擊確定后,就得到了應(yīng)用的信息:

使用django-allauth怎么實(shí)現(xiàn)第三方登錄

其中的Client IDClient Secret就是要用到的憑證。

Django后臺(tái)配置

然后對(duì)Django后臺(tái)進(jìn)行設(shè)置。

進(jìn)入后臺(tái),你會(huì)發(fā)現(xiàn)多了幾個(gè)欄目:

使用django-allauth怎么實(shí)現(xiàn)第三方登錄

打開(kāi)Sites,將example.com修改為博客域名。開(kāi)發(fā)時(shí)則修改為本地IP:

使用django-allauth怎么實(shí)現(xiàn)第三方登錄

然后進(jìn)入Social applications,添加一條applications如下:

使用django-allauth怎么實(shí)現(xiàn)第三方登錄

注意最下面的Sites欄一定要把剛才添加的站點(diǎn)選擇到右邊去。

回到django-allauth的登錄頁(yè)面,點(diǎn)擊github登錄:

使用django-allauth怎么實(shí)現(xiàn)第三方登錄

實(shí)現(xiàn)了GitHub登錄。

allauth配置項(xiàng)

挑幾個(gè)比較重要的講一下。

ACCOUNT_EMAIL_VERIFICATION = 'optional' / 'mandatory' / 'none':當(dāng)其為mandatory時(shí),本地注冊(cè)的用戶必須先驗(yàn)證郵箱才可以登錄。optionalnone都不要求驗(yàn)證郵箱,區(qū)別是optional仍然會(huì)發(fā)送驗(yàn)證郵件,而none連認(rèn)證郵件都不會(huì)發(fā)送。

SOCIALACCOUNT_EMAIL_VERIFICATION = 'optional' / 'mandatory' / 'none':同理,但是作用于第三方賬號(hào)的注冊(cè)。

ACCOUNT_AUTHENTICATION_METHOD = 'username_email' / 'user' / 'email':指定登錄方法,即通過(guò)用戶名、郵箱進(jìn)行登錄,或者兩者均可。

ACCOUNT_EMAIL_REQUIRED = True / False:注冊(cè)本地用戶時(shí),是否必須填寫郵箱。

關(guān)于使用django-allauth怎么實(shí)現(xiàn)第三方登錄就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI