LoginSignup
0
1

Django RestFramework JWT認証についてめも

Last updated at Posted at 2024-02-01

RESTAPIを実装したいので調べてみた

プロフィール

  • Django初めて1ヶ月程度の知識です。

まずは動かしてみる

  1. settings.pyの一番下に追加
settings.py
REST_FRAMEWORK = {
    # jwtトークン認証
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),  
}
SIMPLE_JWT = {
    'AUTH_HEADER_TYPES': ('JWT'),
    # JWT有効期限
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),
}

  1. 適当にアプリを作成python manage.py startapp app1私はapp1というアプリ名で作成した

  2. まずはindex.htmlの表示

app1/views.py
from django.shortcuts import render

def index(self,req):
        return render(req,'app1/index.html')

  1. ここで表示してみたらsettings.pyにapp1を追加してなかったので追加したところ表示できた

ではここからどうやってヘッダにトークンが入っていないものを弾くのか?

  • 例によってわからなかったのでchatGPTさんに質問した
  • そしたら下記のような回答
app1/views.py
from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated


# このクラスがどうやら肝心らしい
class UnauthenticatedView(APIView):
    authentication_classes = [SessionAuthentication]  # Use a different authentication class if needed
    permission_classes = [IsAuthenticated]

    def index(self,req):
        return render(req,'app1/index.html')

def index2(req):
    return render(req,'app1/index2.html')

  1. as_view()こいつがよくわからなかったので再度chatGPTさんに質問
    about_as_view.jpg
  2. ということは書き方変えればいいのかなと試したところ
app1/urls.py
from django.urls import path
from . import views
from .views import UnauthenticatedView

urlpatterns = [
    # 最初はこう書くのかなと思っていた
    # path('', views.UnauthenticatedView.as_view(), name='index'),
    path('', UnauthenticatedView.as_view(), name='index'),
    path('index2/', views.index2),
]

認証弾いた!!!

jwt_err.jpg

まとめ

  • なんでこうやって書くと認証がされるのかこれから解明していく
  • 書き方はなんとなくわかった
  • わかりやすい説明ほしい...
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1