diadia

興味があることをやってみる。自分のメモを残しておきます。

django-rest-authで"detail": "Authentication credentials were not provided."が返される時

参考

Django Rest Framework - Authentication credentials were not provided - Article - Python Decompiler Online

エラーメッセージ

   {"detail": "Authentication credentials were not provided."}

エラーに出くわした状況

rest-authのエンドポイント/rest-auth/password/change/でパスワード変更を試みたが上記のレスポンスが返ってきた。 リクエストはcurlコマンドで送っており、ヘッダーにトークンを添付しているにも関わらず、認証に失敗している状況である。

curl -X POST http://127.0.0.1:8000/rest-auth/password/change/ -d 'new_password1=12345tweet&new_password2=12345tweet&old_password=1234tweet' -H 'Authorization: Token ebfa00bd84de2b8f319b747636270257ec24601c'

解決方法

参考のページと全く同じ方法で解決した。 かんたんに言えば、djangoのsettings.pyにおいてREST_FRAMEWORKを設定することだった。自分の場合は各APIViewのサブクラスの属性情報としてパーミッションの記述や認証の記述を書いて開発してきた。しかしながらdjango-rest-authの場合は認証やパーミッションについて設定されていない。したがってヘッダーにトークンを添付しても認証が行われなかった。 django-rest-authに認証方法を設定するために以下の記述をするとトークンによる認証もうまくいった。

########################
###Django-Rest-Framework###
########################


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
           'rest_framework.authentication.TokenAuthentication',
           'rest_framework.authentication.BasicAuthentication',
       ),
       'DEFAULT_PERMISSION_CLASSES': (
            # https://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy
            #'rest_framework.permissions.IsAdminUser',
            #'rest_framework.permissions.IsAuthenticated',
            #'rest_framework.permissions.AllowAny',
       ),
  }

関連記事

djangoにRESTAPIを実装する メモ - diadia