この記事ではdjango-allauthでtwitter認証をします。
題名を読んで時のごとくなことをやっていきます。
自分はしばらく前まで
social-auth-app-django を使ってtwitter認証の実装をやっていたのですが、いざ他のSNS認証にも手を出そうとするとdjango-allauthがいいよ!という噂を聞いたのでやってみようというわけです。
ではさっそくやっていきます!
djangoのインストール~プロジェクト作成まで
仮想環境の作成とアクティベート
何はともあれ仮想環境です。
今回はtwitterでの認証をひとまず目指すので「twitter-auth」とします。
PS C:\source>virtualenv twitter-auth
PS C:\source>.\Scripts\activate
(twitter-auth) PS C:\source>
django、django-allauthのインストール
これも説明はいらないですね。pipでインストールしてください。
(twitter-auth) PS C:\source> pip install django
(twitter-auth) PS C:\source> pip install django-allauth
djangoのプロジェクトのスタートアップ
プロジェクトのスタートアップを行います。なお、このとき作成した仮想環境に入っておくことを忘れないでください。
(twitter-auth) PS C:\source\twitter-Auth> django-admin startproject mysite
(twitter-auth) PS C:\source\twitter-Auth> cd .\mysite
(twitter-auth) PS C:\source\twitter-Auth\mysite> django-admin startapp twitAuth
migration と runserver
それでは最後にマイグレーションをしてrunserverしてdjangoサーバーの起動を確認しましょう。
(twitter-auth) PS C:\source\twitter-auth\mysite> python manage.py makemigrations
No changes detected
(twitter-auth) PS C:\source\twitter-auth\mysite> python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
(twitter-auth) PS C:\source\twitter-auth\mysite> python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
July 24, 2019 - 21:08:18
Django version 2.2.3, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
無事djangoサーバの起動に成功したら、 http://127.0.0.1:8000/ にアクセスして……。

これで認証機能を実装するプロジェクトとアプリケーションが作成できました。次の章からは実際にコーディングをしていきます。
なおここまででうまく行かないは、以下の記事を参考にしてみてください。
django-allauthによるtwitter認証
settings.pyの設定
まずはallauth関連のアプリケーションをdjangoに登録します。
アプリを追加したらマイグレーションをしておくことを忘れないでください。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Up here is all your default installed apps from Django
# The following apps are required:
'django.contrib.sites',
'allauth', #追加
'allauth.account', #追加
'allauth.socialaccount', #追加
# include the providers you want to enable:
'allauth.socialaccount.providers.twitter', #追加
]
今回templateは自前で用意するので、そのディレクトリも定義しておきます。
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',
'django.template.context_processors.request',
],
},
},
]
そして最後に以下の設定を付け加えて、settings.pyの設定は完了です。
LOGIN_REDIRECT_URLとACCOUNT_LOGOUT_REDIRECT_URLはそれぞれログイン後、ログアウト後にリダイレクトするurlの指定です。別途urls.pyに定義するurlにつける名称を定義しておきます。
SITE_ID = 1
LOGIN_REDIRECT_URL = 'home'
ACCOUNT_LOGOUT_REDIRECT_URL = 'top'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
"allauth.account.auth_backends.AuthenticationBackend",
)
プロジェクトのurls.py
プロジェクトのurls.pyを記述します。
今回はallauthのurlpatternsを使おうと思うので、includeして追加します。
urlpatterns = [
path('admin/', admin.site.urls),
path('', TemplateView.as_view(template_name='top.html'), name='top'), #追加
path('home/', TemplateView.as_view(template_name='home.html'), name='home'), #追加
path('auth/', include('allauth.urls')), #追加
]
ちなみにallauthのurlsはソースから見ることができるので気になる人は参考にしてください。
C:\source\twitter-auth\Lib\site-packages\allauth\account のurls.pyです。
templatesたち、ログインとかホーム画面とか
まずはtop画面のhtmlです。今回は簡単に行きたいのでデザインとか気にしません。
[templates/top.html]
<a href="{%url 'account_login'%}">ログイン画面へ</a>
はたして需要があるのか!?ログイン画面へのリンクだけを貼っておきます。
次にログイン画面です。twitterでログインのリンクだけ表示してあります。ここがちょっと重要なのですが、twitter_loginという名前のurlへのリンクを踏むとtwitterでログインすることができます。
[templates/account/login.html]
<a href="{% url 'twitter_login' %}">Twitterでログイン</a>
そして最後にホーム画面……これはログイン後のリダイレクト先ですね。
[templates/home.html]
<p>ほーむ</p>
<a href="{%url 'account_logout'%}">ログアウト</a>
ログアウト画面を作るのは面倒だったので、ここに含めちゃいました。
さて、とりあえずコーディングはこれでおしまいです。
twitter-APIKeyの登録
「え!?もうコーディング終わりなの?」
と驚く人がいるかも知れません。
なぜならtwitter認証を行うにはtwitterアプリを作らねばならず、そのアプリの認証用のAPIKeyが必要だからです。今までの段階ではソースに含まれてきていません。
実はdjango-allauthでは、APIKeyはdjangoの管理サイトで登録するのです。
さっそく管理サイトにログインしていきましょう。
まずはスーパーユーザを作成します。
(twitter-auth) PS C:\source\twitter-auth\mysite> python manage.py createsuperuser
ユーザー名 (leave blank to use '*****'):
メールアドレス:
Password:
Password (again):
Superuser created successfully.
そしたら http://127.0.0.1:8000/admin にアクセスしてログインします。
ログインしたら外部アカウントの Social applications を選択します。

次にsocial applicationの追加をして…。

最後に追加したアプリケーションを設定します。

SNS認証のプロバイダ、認証の名前、APIKeyとSecretKeyを設定してください。
twitterのAPIKeyなんかの取得方法はいつか記事にしたいと想います。
ここまでくればログインできるはずです。
トップページからログインページに飛んでLet’sTry!
まとめ
以上で駆け足でしたがdjango-allauthでのtwitter認証でした。
実装してみた印象ですが、思ったより簡単ですね。
特にurlリンクを埋め込むだけでやれるので簡単だなーと思った次第です。
昨今のようなWEBアプリ乱立時代には、こういうSNS認証があるかないかだけでだいぶ使いやすさに差が出るような気がしますね-。
コメント