Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Django REST Frameworkに再挑戦 その24 Django Rest Framework JWT & Curl Tests

概要

Django REST Frameworkに再挑戦 その24 Django Rest Framework JWT & Curl Tests

参考サイト

www.django-rest-framework.org

www.codingforentrepreneurs.com

Django Rest Framework JWT & Curl Tests

  • Django Rest Framework JWTの公式ページをチェックしてみる。認証関連のpackage。JSON Web Token Authentication support for Django REST framework.らしい。

Django REST framework JWT

  • $ pip install djangorestframework-jwtする。

  • settings.pyのREST FRAMEWORKの設定に以下のように追記する。

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    # 'DEFAULT_PARSER_CLASSES': (
    #     'rest_framework.parsers.JSONParser',
    # ),
    'DEFAULT_AUTHENTICATION_CLASSES':(
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication', #'rest_framework.authentication.BasicAuthentication', #こちらはオススメしないとのこと。
    ),
    'DEFAULT_PERMISSION_CLASSES':(
        'rest_framework.permissions.IsAuthenticated',
    ),

}
  • rest_framework.authentication.SessionAuthenticationコメントアウトしてもOK。

  • urls.pyに、JWT用のurlを設定する。

from rest_framework_jwt.views import obtain_jwt_token
#...

urlpatterns = patterns(
    '',
    # ...

    url(r'^api/auth/token/', obtain_jwt_token), # urlの箇所だけ微妙に変えてある。
)
  • テスト用のshell スクリプトも用意されているので、settings.pyなどにメモっておく。
'''
You can easily test if the endpoint is working by doing the following in your terminal, if you had a user created with the username admin and password password123.

$ curl -X POST -d "username=user名&password=********" http://127.0.0.1:8000/api/auth/token/
'''
  • シェルで、$ curl -X POST -d "username=user名&password=********" http://127.0.0.1:8000/api/auth/token/ を打って、tokenが表示されたらOK。

  • テストとして、シェルに表示されたtokenをメモっておき、次のテストに使う。

  • 先ずは、curl http://127.0.0.1:8000/api/comments/ としておき、認証が必要なサイトに行ってみる。。。{"detail":"Authentication credentials were not provided."}と表示されたので、取得できなかったことがわかる。

  • 次に、$ curl -H "Authorization: JWT <your_token>" http://127.0.0.1:8000/api/comments/でアクセスしてみる。。。取得できた〜〜!

  • さらに、commentの投稿も試してみる。ヘッダー2つで、パスとコンテンツ部分を渡す。

curl -X POST -H "Authorization: JWT ***********************************.*********************************.-1XWtO99XlA75fahKjLdSLxfa3f6kbDo1qpcCmUTopE" -H "Content-Type: application/json" -d '{"content":"this is content"}' 'http://127.0.0.1:8000/api/comments/create/?slug=my-title&type=post'
  • さらに、parent_idでスレッドにもコメントできるか確認する。
curl -X POST -H "Authorization: JWT ***********************************.*********************************.-1XWtO99XlA75fahKjLdSLxfa3f6kbDo1qpcCmUTopE" -H "Content-Type: application/json" -d '{"content":"this is content"}' 'http://127.0.0.1:8000/api/comments/create/?slug=my-title&type=post&parent_id'
  • これは便利やな〜!