JWTログイン後にリクエストを投稿/取得する際に問題が発生しました。(私はdjangorestframework-jwtライブラリを使用しています)ユーザーが正常にログインすると、アプリはjsonトークンを返しますが、このトークンを次のリクエストに使用すると、
{
"detail": "Authentication credentials were not provided."
}
settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
JWT_AUTH = {
'JWT_ALLOW_REFRESH': True,
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1),
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
}
ログインビュー
def post(self, request, format=None):
if not request.data:
return Response({'Error': "Please provide username/password"}, status=status.HTTP_400_BAD_REQUEST)
username = request.data['username']
password = request.data['password']
try:
user = User.objects.get(email=username, password=password)
except User.DoesNotExist:
return Response({'Error': "Invalid username/password"}, status=status.HTTP_400_BAD_REQUEST)
if user:
payload = {
'id': user.id,
'email': user.email,
'first_name': user.first_name
}
jwt_token = jwt.encode(payload, "SECRET_KEY") # to be changed
return Response({'token': jwt_token}, status=status.HTTP_200_OK)
その後、他のすべてのビューに含まれています
authentication_class = (JSONWebTokenAuthentication,)
permission_classes = (IsAuthenticated,)
postmanとcurlの両方でテストしましたが、同じエラーが発生します。ヘッダー形式にエラーがあるのか、それともsmthがあるのかわからないので、私は行方不明です。どんな助けでも大歓迎です!
編集:設定をに変更しました
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
しかし今私はそれを得る
{
"detail": "Error decoding signature."
}
編集:問題は、jwt_token = jwt.encode(payload, 'SECRET_KEY')
認識されないトークンを返す可能性があることだと思います...それによって生成されたトークンを使用する場合、obtain_jwt_token
任意のエンドポイントにクエリを実行できます。誰かがこれを説明できますか?
編集:に変更しjwt_token = jwt_encode_handler(payload)
、設定ファイルにJWT_SECRET_KEY
(jwtにログインした後に受け取ったトークンを確認すると、それは確かに正しいペイロードとシークレットを持つ正しいトークンです)が含まれていますが、それでも認識されません"detail": "Invalid signature."
私はなんとか問題を解決することができました。ユーザーを認証するとき、私はuser
以前に作成したカスタムテーブルと照合していました。これはdjangoのauth_user
テーブルとは異なります。カスタムユーザーテーブルを使用するようにdjangoの設定を変更した後、認証からのトークンを使用して他のリクエストでも機能しました。
AUTH_USER_MODEL = 'main.User'
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加