よしたく blog

ほぼ週刊で記事を書いています

Django REST FrameworkとJWTで認証を実装する

手順

インストール

まずはDjango REST FrameworkとJWTを扱うためのライブラリをインストールします。

pip install djangorestframework
pip install djangorestframework-jwt

Django REST Frameworkの設定

プロジェクトとアプリケーションの作成

次にDjango REST Frameworkのプロジェクトを作成します。django-admin startproject config .でルートフォルダ直下にconfigフォルダが出来上がります。必須ではないですが実際の環境を想定し、apiアプリケーションも作成しておきます。

django-admin startproject config .
django-admin startapp api

設定ファイルの編集

config/settings.pyにデフォルトの許可設定と認証のクラスを記述します。

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

config/urls.pyにJWTを使うためのimport文from rest_framework_jwt.views import obtain_jwt_tokenとurlpatternsの中にエンドポイントを設定するpath('api-token-auth/', obtain_jwt_token),を記述します。

from django.contrib import admin
from django.urls import path

from rest_framework_jwt.views import obtain_jwt_token


urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-token-auth/', obtain_jwt_token),
]

スーパーユーザの作成とマイグレーション

python manage.py createsuperuser
user name : admin
password Passw0rd1234
python manage.py migrate

実行

サーバを起動する。

python manage.py runserver 0.0.0.0:8000

curlで設定したURLにusernameとpasswordを投げてみるとtokenが返ってきます。

curl -X POST -d "username=admin&password=Passw0rd1234" http://localhost:8000/api-token-auth/
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTg1MTExODM1LCJlbWFpbCI6IiJ9.cDKEDtt3dPNRQREGrC3JRuu0XzHSNSzkzdp_kvQONyQ"}```

リポジトリはこちら
[https://github.com/yoshitaku-jp/sandbox-DRF-JWT:embed:cite]