from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions
This example authentication is straight from the official docs here.
class ExampleAuthentication(BaseAuthentication):
def authenticate(self, request):
username = request.META.get('X_USERNAME')
if not username:
return None
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise AuthenticationFailed('No such user')
return (user, None)
There are four parts to a custom authentication class.
authenticate
taking request
as first argument.AuthenticationFailed
exception for a failed authentication. This is available in rest_framework.authentication.class SecretAuthentication(BaseAuthentication):
def authenticate(self, request):
app_key = request.META.get('APP_KEY')
app_secret = request.META.get('APP_SECRET')
username = request.META.get('X_USERNAME')
try:
app = ClientApp.objects.match_secret(app_key, app_secret)
except ClientApp.DoesNotExist:
raise AuthenticationFailed('App secret and key does not match')
try:
user = app.users.get(username=username)
except User.DoesNotExist:
raise AuthenticationFailed('Username not found, for the specified app')
return (user, None)
The authentication scheme will return HTTP 403 Forbidden responses when an unauthenticated request is denied access.