Dango REST JWT authentication totally misunderstanding

49 views Asked by At

Hello im trying to make MSA login/register in my project. I tried to implement it with JWT

I understand the concept, i understand what happens in the start and in the end. But have no clue what's in the middle

How to login my user with this token?

Look

My login template. I have AJAX to call the function on the core app, that then will call TOKEN SERVICE

{% extends 'main.html' %}
{% load static %}
{% block content %}

<link rel="stylesheet" type="text/css" href="{% static 'styles/popup.css' %}">
{% if status == 'success' %}

    <div class="popup-container">
        <div class="popup">
        <p class="popup-message">Something went wrong while processing request. Please try again.<br> Or, <a href="#">Report Problem</a></p>
        <button class="popup-close-button" type="button"><i class="fas fa-times"></i></button>
        </div>
    </div>

    <div class="formcontainer">
        <div class="container mt-5">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <h2 class="mb-4">User Login</h2>

                    <form method="post" class="LoginForm">

                        {% csrf_token %}

                        <div class="form-group">
                            <label>Email</label>
                            <input type="text" name="email" id="email" class="form-control" placeholder="e.g [email protected]" required >
                        </div>

                        <div class="form-group">
                            <label>Password</label>
                            <input type="password" name="password" id="password" class="form-control" placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;" required >
                            <small style="display: flex; justify-content: right; margin-top: 10px;">Haven't signed up yet?&nbsp;<a href="{% url 'register_page' %}">Sign Up</a></small>
                            <small style="color: red; display: flex; justify-content: center; margin-top: 10px; display: none">Invalid Credentials</small>
                        </div>

                        <button type="submit" class="btn btn-primary" style="margin-bottom: 15px;">Login</button>
                    </form>

                </div>
            </div>
        </div>
    </div>
{% else %}
    {% include '500.html' %}
{% endif %}
<script>
    $(document).ready(function() {
        $('.LoginForm').on('submit', function(event) {
            event.preventDefault();
            console.log('clicked');
            var formData = new FormData(this);

            $.ajax({
                url: `{% url 'login_processing' %}`, 
                type: 'POST',
                data: formData,
                processData: false, 
                contentType: false,  
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}'
                  },
                success: function(data) {
                    
                    if (data.STATUS === 'SUCCESS') {
                        console.log('success');
                        location.reload();

                    }
                    if (data.STATUS === 'NOT VALID') {
                        console.log('not valid')
                    }
                    if (data.STATUS === 'FAILED') {
                        console.log('failed')
                    }
                },
                error: function(data) {
                    console.log('error');
                }
            })
        })
    })

</script>
{% endblock content %}

There is my core-app function between microservice and frontend. Don't judge this - it's just a sketch

async def login_processing(request: HttpRequest) -> Union[HttpResponse, JsonResponse]:
        
        # try:
            
            if request.method == 'POST':
                
                async with aiohttp.ClientSession() as session:
                    response = await session.post('http://127.0.0.1:8080/api/token/', data=
                                                  {"email": "[email protected]","password": "Lovell32bd"})
                response_json = await response.json()
                
                print(response_json)
                return JsonResponse({'STATUS':'OK'})

This is my microservice on DRF

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework import status, views

from django.shortcuts import render
from django.http import JsonResponse, HttpRequest, HttpResponse
from django.contrib.auth import authenticate, login

from ..models import *
from .serializers import *

import django
import datetime
import jwt

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

@api_view(['GET'])
def getRoutes(request: HttpRequest):
    routes = [
        'GET /api',
        'POST /api/register',
        'POST /api/login',
        'POST api/token/',
        'POST api/token/refresh/'
    ]
    return Response(routes)


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # Add custom claims
        token['email'] = user.email
        # ...

        return token

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

This is settings of microservice

"""
Django settings for login_register_ms project.

Generated by 'django-admin startproject' using Django 4.1.7.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

import os
import dotenv
from datetime import timedelta
dotenv.load_dotenv()


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cities_light',
    'base',
    'rest_framework',
    'rest_framework_simplejwt',
    'rest_framework_simplejwt.token_blacklist',
]


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'login_register_ms.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'login_register_ms.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': os.getenv('DEFAULT_ENGINE'),
        'OPTIONS': {
                'options': '-c search_path=public'
            },
        'NAME': os.getenv('DEFAULT_NAME'),
        'USER': os.getenv('DEFAULT_USER'),
        'PASSWORD': os.getenv('DEFAULT_PASSWORD'),
        'HOST': os.getenv('DEFAULT_HOST'),  
        'PORT': os.getenv('DEFAULT_PORT'),      
    },
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


AUTH_USER_MODEL = os.getenv('AUTH_USER_MODEL')
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [ 
        'rest_framework_simplejwt.authentication.JWTAuthentication', 
    ],
}

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=90),
    "ROTATE_REFRESH_TOKENS": True,
    "BLACKLIST_AFTER_ROTATION": True,
    "UPDATE_LAST_LOGIN": False,

    "ALGORITHM": "HS256",
    # "SIGNING_KEY": '',
    "VERIFYING_KEY": "",
    "AUDIENCE": None,
    "ISSUER": None,
    "JSON_ENCODER": None,
    "JWK_URL": None,
    "LEEWAY": 0,

    "AUTH_HEADER_TYPES": ("Bearer",),
    "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
    "USER_ID_FIELD": "id",
    "USER_ID_CLAIM": "user_id",
    "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule",

    "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
    "TOKEN_TYPE_CLAIM": "token_type",
    "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser",

    "JTI_CLAIM": "jti",

    "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
    "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
    "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),

    "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer",
    "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer",
    "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer",
    "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer",
    "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer",
    "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer",
}
0

There are 0 answers