LoginSignup
1
0

More than 1 year has passed since last update.

Django REST frameworkのAuthenticationのカスタマイズ

Posted at

Authenticationについて

認証を行っている部分。
DRFではデフォルトで以下のパターンが用意されている。

  • BasicAuthentication
  • TokenAuthentication
  • SessionAuthentication
  • RemoteUserAuthentication

ただJWT認証などをやりたい場合は自作する or 外部ライブラリを使う必要がある。
今回は自作する場合について述べる。

 BaseAuthentication

独自の認証方式を実装するには、BaseAuthenticationをサブクラスにして、 .authenticate(self, request)メソッドをオーバーライドする。このメソッドは、認証に成功した場合は (user, auth) のタプルを、そうでない場合はNoneを返す。

例外は2種類ある。

  • Noneをreturnする: 認証スキップする場合。ログインが必須でないときや他の認証方法も試すときはこっち
  • AuthenticationFailed`をraiseする: 直ちにエラーメッセージを返す場合。ログイン必須はこっち

.authenticate_header(self, request) メソッドをオーバーライドすることもできます。実装する場合は、HTTP 401 Unauthorized レスポンスの WWW-Authenticate ヘッダーの値として使用される文字列を返す必要があります。

.authenticate_header() メソッドをオーバーライドしない場合、認証スキームは、認証されていないリクエストのアクセスが拒否されたときに HTTP 403 Forbidden レスポンスを返します。

auth.py.py

from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        username = request.META.get('HTTP_X_USERNAME')# カスタムリクエストHeaderであるX_USERNAMEから値取得
        if not username:
            return None

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')

        return (user, None)

参考文献

1
0
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
1
0