User Authentication with Django REST Framework and JSON Web Tokens

""" def _create_user(self, username, email, password=None, **extra_fields): if not username: raise ValueError('The given username must be set') if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) return user def create_user(self, username, email, password=None, **extra_fields): """ Create and return a `User` with an email, username and password..""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(username, email, password, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): """ Create and return a `User` with superuser (admin) permissions..""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, email, password, **extra_fields)There is a lot of code that was dumped out just now but my goal is to get you up and running as soon as possible..I recommend reading through the code line by line to make sure you understand what is going on (this is generally a good idea whenever you are copying code from the internet!)!.The User class and UserManager are all you need to create a custom user in Django..Just don’t forget to let Django know that these models exist by declaring your app in the file:INSTALLED_APPS = [ ….'rest_framework', 'authentication', # My'authentication` app …]AUTH_USER_MODEL = 'authentication.User'Authentication BackendBy default, Django does not know how to authenticate your JWTs..To fix this, we must the create the following file:import jwtfrom django.conf import settingsfrom rest_framework import authentication, exceptionsfrom .models import Userclass JWTAuthentication(authentication.BaseAuthentication): authentication_header_prefix = 'Bearer' def authenticate(self, request): """ The `authenticate` method is called on every request regardless of whether the endpoint requires authentication. `authenticate` has two possible return values: 1) `None` – We return `None` if we do not wish to authenticate. Usually this means we know authentication will fail. An example of this is when the request does not include a token in the headers. 2) `(user, token)` – We return a user/token combination when authentication is successful. If neither case is met, that means there's an error and we do not return anything. We simple raise the `AuthenticationFailed` exception and let Django REST Framework handle the rest. """ request.user = None # `auth_header` should be an array with two elements: 1) the name of # the authentication header (in this case, "Token") and 2) the JWT # that we should authenticate against..auth_header = authentication.get_authorization_header(request).split() auth_header_prefix = self.authentication_header_prefix.lower() if not auth_header: return None if len(auth_header) == 1: # Invalid token header..No credentials provided..Do not attempt to # authenticate..return None elif len(auth_header) > 2: # Invalid token header.. More details

Leave a Reply