added custom JWT authentication
This commit is contained in:
parent
7a1d5e269c
commit
39e833ec1d
|
|
@ -200,8 +200,11 @@ class LogoutSerializer(serializers.ModelSerializer):
|
||||||
def validate(self, attrs):
|
def validate(self, attrs):
|
||||||
"""Override validated data"""
|
"""Override validated data"""
|
||||||
request = self.context.get('request')
|
request = self.context.get('request')
|
||||||
token = request.headers.get('Authorization') \
|
# Get token bytes from cookies (result: b'Bearer <token>')
|
||||||
.split(' ')[::-1][0]
|
token_bytes = utils_methods.get_token_from_cookies(request)
|
||||||
|
# Get token value from bytes
|
||||||
|
token = token_bytes.decode().split(' ')[::-1][0]
|
||||||
|
# Get access token obj
|
||||||
access_token = tokens.AccessToken(token)
|
access_token = tokens.AccessToken(token)
|
||||||
# Prepare validated data
|
# Prepare validated data
|
||||||
attrs['user'] = request.user
|
attrs['user'] = request.user
|
||||||
|
|
|
||||||
36
apps/utils/authentication.py
Normal file
36
apps/utils/authentication.py
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
"""Custom authentication based on JWTAuthentication class"""
|
||||||
|
from rest_framework import HTTP_HEADER_ENCODING
|
||||||
|
from rest_framework_simplejwt.authentication import JWTAuthentication
|
||||||
|
from rest_framework_simplejwt.settings import api_settings
|
||||||
|
|
||||||
|
from utils.methods import get_token_from_cookies
|
||||||
|
|
||||||
|
AUTH_HEADER_TYPES = api_settings.AUTH_HEADER_TYPES
|
||||||
|
|
||||||
|
if not isinstance(api_settings.AUTH_HEADER_TYPES, (list, tuple)):
|
||||||
|
AUTH_HEADER_TYPES = (AUTH_HEADER_TYPES,)
|
||||||
|
|
||||||
|
AUTH_HEADER_TYPE_BYTES = set(
|
||||||
|
h.encode(HTTP_HEADER_ENCODING)
|
||||||
|
for h in AUTH_HEADER_TYPES
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class GMJWTAuthentication(JWTAuthentication):
|
||||||
|
"""
|
||||||
|
An authentication plugin that authenticates requests through a JSON web
|
||||||
|
token provided in a request cookies.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def authenticate(self, request):
|
||||||
|
token = get_token_from_cookies(request)
|
||||||
|
if token is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
raw_token = self.get_raw_token(token)
|
||||||
|
if raw_token is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
validated_token = self.get_validated_token(raw_token)
|
||||||
|
|
||||||
|
return self.get_user(validated_token), None
|
||||||
|
|
@ -73,7 +73,7 @@ class NotValidUsernameError(exceptions.APIException):
|
||||||
class NotValidTokenError(exceptions.APIException):
|
class NotValidTokenError(exceptions.APIException):
|
||||||
"""The exception should be thrown when token in url is not valid
|
"""The exception should be thrown when token in url is not valid
|
||||||
"""
|
"""
|
||||||
status_code = status.HTTP_400_BAD_REQUEST
|
status_code = status.HTTP_401_UNAUTHORIZED
|
||||||
default_detail = _('Not valid token')
|
default_detail = _('Not valid token')
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,13 +16,23 @@ def generate_code(digits=6, string_output=True):
|
||||||
return str(value) if string_output else value
|
return str(value) if string_output else value
|
||||||
|
|
||||||
|
|
||||||
|
def get_token_from_cookies(request):
|
||||||
|
"""Get access token from request cookies"""
|
||||||
|
cookies = request.COOKIES
|
||||||
|
if cookies.get('access_token'):
|
||||||
|
token = f'Bearer {cookies.get("access_token")}'
|
||||||
|
return token.encode()
|
||||||
|
|
||||||
|
|
||||||
def get_token_from_request(request):
|
def get_token_from_request(request):
|
||||||
"""Get access token from request"""
|
"""Get access token from request"""
|
||||||
|
token = None
|
||||||
if 'Authorization' in request.headers:
|
if 'Authorization' in request.headers:
|
||||||
if isinstance(request, HttpRequest):
|
if isinstance(request, HttpRequest):
|
||||||
return request.headers.get('Authorization').split(' ')[::-1][0]
|
token = request.headers.get('Authorization').split(' ')[::-1][0]
|
||||||
elif isinstance(request, Request):
|
if isinstance(request, Request):
|
||||||
return request._request.headers.get('Authorization').split(' ')[::-1][0]
|
token = request.headers.get('Authorization').split(' ')[::-1][0]
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
def username_validator(username: str) -> bool:
|
def username_validator(username: str) -> bool:
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,10 @@
|
||||||
"""Project custom permissions"""
|
"""Project custom permissions"""
|
||||||
from rest_framework.permissions import BasePermission
|
from rest_framework.permissions import BasePermission
|
||||||
|
from rest_framework_simplejwt.exceptions import TokenBackendError
|
||||||
|
|
||||||
from authorization.models import BlacklistedAccessToken
|
from authorization.models import BlacklistedAccessToken
|
||||||
from utils.methods import get_token_from_request
|
from utils.exceptions import NotValidTokenError
|
||||||
|
from utils.methods import get_token_from_cookies
|
||||||
|
|
||||||
|
|
||||||
class IsAuthenticatedAndTokenIsValid(BasePermission):
|
class IsAuthenticatedAndTokenIsValid(BasePermission):
|
||||||
|
|
@ -12,12 +15,17 @@ class IsAuthenticatedAndTokenIsValid(BasePermission):
|
||||||
def has_permission(self, request, view):
|
def has_permission(self, request, view):
|
||||||
"""Check permissions by access token and default REST permission IsAuthenticated"""
|
"""Check permissions by access token and default REST permission IsAuthenticated"""
|
||||||
user = request.user
|
user = request.user
|
||||||
if user and user.is_authenticated:
|
try:
|
||||||
token = get_token_from_request(request)
|
if user and user.is_authenticated:
|
||||||
# Check if user access token not expired
|
token_bytes = get_token_from_cookies(request)
|
||||||
expired = BlacklistedAccessToken.objects.by_token(token)\
|
# Get access token key
|
||||||
.by_user(user)\
|
token = token_bytes.decode().split(' ')[1]
|
||||||
.exists()
|
# Check if user access token not expired
|
||||||
return not expired
|
blacklisted = BlacklistedAccessToken.objects.by_token(token) \
|
||||||
|
.by_user(user) \
|
||||||
|
.exists()
|
||||||
|
return not blacklisted
|
||||||
|
except TokenBackendError:
|
||||||
|
raise NotValidTokenError()
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
|
|
|
||||||
|
|
@ -67,8 +67,8 @@ class JWTGenericViewMixin(generics.GenericAPIView):
|
||||||
"""Update COOKIES in response from namedtuple"""
|
"""Update COOKIES in response from namedtuple"""
|
||||||
for cookie in cookies:
|
for cookie in cookies:
|
||||||
# todo: remove config for develop
|
# todo: remove config for develop
|
||||||
import os
|
from os import environ
|
||||||
configuration = os.environ.get('SETTINGS_CONFIGURATION', None)
|
configuration = environ.get('SETTINGS_CONFIGURATION', None)
|
||||||
if configuration == 'development':
|
if configuration == 'development':
|
||||||
response.set_cookie(key=cookie.key,
|
response.set_cookie(key=cookie.key,
|
||||||
value=cookie.value,
|
value=cookie.value,
|
||||||
|
|
|
||||||
|
|
@ -205,10 +205,9 @@ REST_FRAMEWORK = {
|
||||||
'DEFAULT_PAGINATION_CLASS': 'utils.pagination.ProjectMobilePagination',
|
'DEFAULT_PAGINATION_CLASS': 'utils.pagination.ProjectMobilePagination',
|
||||||
'COERCE_DECIMAL_TO_STRING': False,
|
'COERCE_DECIMAL_TO_STRING': False,
|
||||||
'DEFAULT_AUTHENTICATION_CLASSES': (
|
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||||
'rest_framework.authentication.TokenAuthentication',
|
|
||||||
'rest_framework.authentication.SessionAuthentication',
|
|
||||||
# JWT
|
# JWT
|
||||||
'rest_framework_simplejwt.authentication.JWTAuthentication',
|
'utils.authentication.GMJWTAuthentication',
|
||||||
|
'rest_framework.authentication.SessionAuthentication',
|
||||||
),
|
),
|
||||||
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning',
|
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning',
|
||||||
'DEFAULT_VERSION': (AVAILABLE_VERSIONS['current'],),
|
'DEFAULT_VERSION': (AVAILABLE_VERSIONS['current'],),
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,3 @@ API_HOST_URL = 'http://%s' % API_HOST
|
||||||
BROKER_URL = 'amqp://rabbitmq:5672'
|
BROKER_URL = 'amqp://rabbitmq:5672'
|
||||||
CELERY_RESULT_BACKEND = BROKER_URL
|
CELERY_RESULT_BACKEND = BROKER_URL
|
||||||
CELERY_BROKER_URL = BROKER_URL
|
CELERY_BROKER_URL = BROKER_URL
|
||||||
|
|
||||||
# Increase access token lifetime for local deploy
|
|
||||||
SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'] = timedelta(days=365)
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user