API Tokens #134
@ -277,6 +277,7 @@ REST_FRAMEWORK = {
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||
'rest_framework.authentication.SessionAuthentication',
|
||||
'rest_framework.authentication.BasicAuthentication',
|
||||
dfelinto marked this conversation as resolved
Outdated
|
||||
'tokens.authentication.UserTokenAuthentication',
|
||||
),
|
||||
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
|
||||
}
|
||||
|
25
tokens/authentication.py
Normal file
25
tokens/authentication.py
Normal file
@ -0,0 +1,25 @@
|
||||
from rest_framework.authentication import BaseAuthentication
|
||||
from rest_framework.exceptions import AuthenticationFailed
|
||||
from .models import UserToken
|
||||
|
||||
|
||||
class UserTokenAuthentication(BaseAuthentication):
|
||||
def authenticate(self, request):
|
||||
auth_header = request.headers.get('Authorization')
|
||||
|
||||
if not auth_header:
|
||||
return None
|
||||
|
||||
try:
|
||||
token_type, token_key = auth_header.split()
|
||||
if token_type.lower() != 'bearer':
|
||||
return None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
try:
|
||||
token = UserToken.objects.get(token=token_key)
|
||||
except UserToken.DoesNotExist:
|
||||
raise AuthenticationFailed('Invalid token')
|
||||
|
||||
return (token.user, token)
|
Loading…
Reference in New Issue
Block a user
why do we need SessionAuthentication and BasicAuthentication?
if we plan to use only our own UserTokenAuthentication, checking the header on each request, we won't need the other mechanisms