Lymaa Lymaa

Lymaa Lymaa

1621833483

Authenticate With Djoser

REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such as registration, login, logout, password reset and account activation. It works with custom user model.

Requirements:

Project Setup:

create a virtual env.

python -m venv env

Activate
./env/Scripts/activate # for windows

source env/bin/activate # linux user

Here i am using poetry you can use pip or pienv:
poetry Setup:

    poetry init
    poetry add django djangorestframework djoser djangorestframework_simplejwt django-cors-headers
    poetry add drf-yasg # for api docs

Creating project and apps:

    django-admin startproject core
    python manage.py startapp accounts

Configuring settings.py:

# Installed Apps

DJANGO_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]

PROJECT_APPS = ["accounts"]

THIRD_PARTY_APPS = [
"rest_framework",
"drf_yasg",
"djoser",
"corsheaders",
"rest_framework_simplejwt",
"rest_framework_simplejwt.token_blacklist",
]

INSTALLED_APPS = DJANGO_APPS + PROJECT_APPS + THIRD_PARTY_APPS

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware", # middleware for cors-headers
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

let’s create a customuser model:

accounts/models.py

from django.db import models
from django.contrib.auth.models import (
    AbstractBaseUser,
    PermissionsMixin,
    BaseUserManager,
)


class CustomUserManager(BaseUserManager):
    def create_user(self, email, username, password=None, **extra_fields):
        if not email:
            raise ValueError("User must have an email")
        email = self.normalize_email(email)
        user = self.model(email=email, username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email, password=None, **extra_fields):
        user = self.create_user(username, email, password=password, **extra_fields)
        user.is_active = True
        user.is_staff = True
        user.is_admin = True
        user.save(using=self._db)
        return user


class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    username = models.CharField(max_length=255, unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)

    objects = CustomUserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["username", "first_name", "last_name"]

    def get_full_name(self):
        return f"{self.first_name} - {self.last_name}"

    def get_short_name(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    def __str__(self):
        return self.email

Customizing Serializers

accounts/serializers.py

from djoser.serializers import UserCreateSerializer
from django.contrib.auth import get_user_model

User = get_user_model()


class UserCreateSerializer(UserCreateSerializer):
    class Meta(UserCreateSerializer.Meta):
        model = User
        fields = ("id", "email", "username", "first_name", "last_name", "password")

Email setup: settings.py

# EMAIL CONFIG
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "localhost"
EMAIL_PORT = "1025"
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""
EMAIL_USE_TLS = False

Djoser JWT and CORS HEADERS: settings.py

[Note: you won’t need cors header unless you use any frontend framework]

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ),
}


SIMPLE_JWT = {
    "AUTH_HEADER_TYPES": ("JWT",),
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
    "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
}

# DJOSER CONFIG
DJOSER = {
    "LOGIN_FIELD": "email",
    "USER_CREATE_PASSWORD_RETYPE": True,
    "USERNAME_CHANGED_EMAIL_CONFIRMATION": True,
    "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True,
    "SEND_CONFIRMATION_EMAIL": True,
    "SET_USERNAME_RETYPE": True,
    "SET_PASSWORD_RETYPE": True,
    "USERNAME_RESET_CONFIRM_URL": "password/reset/confirm/{uid}/{token}",
    "PASSWORD_RESET_CONFIRM_URL": "email/reset/confirm/{uid}/{token}",
    "ACTIVATION_URL": "activate/{uid}/{token}",
    "SEND_ACTIVATION_EMAIL": True,
    "SOCIAL_AUTH_TOKEN_STRATEGY": "djoser.social.token.jwt.TokenStrategy",
    "SOCIAL_AUTH_ALLOWED_REDIRECT_URIS": [
        "your redirect url",
        "your redirect url",
    ],
    "SERIALIZERS": {
        "user_create": "accounts.serializers.UserCreateSerializer",  # custom serializer
        "user": "djoser.serializers.UserSerializer",
        "current_user": "djoser.serializers.UserSerializer",
        "user_delete": "djoser.serializers.UserSerializer",
    },
}

# CORS HEADERS
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

URL CONFIG:

  • accounts/urls.py
from django.urls import path


urlpatterns = []

  • main/urls.py
#main/urls.py

from django.contrib import admin
from django.urls import path
from django.urls.conf import include, re_path

# DRF YASG
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="Djoser API",
        default_version="v1",
        description="REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such as registration, login, logout, password reset and account activation. It works with custom user model.",
        contact=openapi.Contact(email="contact@snippets.local"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    path("admin/", admin.site.urls),
    re_path(
        r"^api/v1/docs/$",
        schema_view.with_ui("swagger", cache_timeout=0),
        name="schema-swagger-ui",
    ),
    path("api/v1/", include("accounts.urls")),
    path("api/v1/", include("djoser.urls")),
    path("api/v1/", include("djoser.urls.jwt")),
    
]

Here we:

  1. include some url paths that djoser provides us.
  2. and config for API docs
    http://127.0.0.1:8000/api/v1/docs/
    Alt Text
    Api docs

here are some urls:

Requires two parameters:
{
“uid” :“some uid”,
“token”: “some token”
}
postman
Similarly you can work with below apis.

we can work with social-auth too but we require extra configs.
here is the github link where i have work with social auth

overall we are done. 😌😌😌😌
If you are stuck 👇👇👇.


IMAGE ALT TEXT HERE Github


#django #python #djoser #jwt #rest-api #authenticate

What is GEEK

Buddha Community

Authenticate With Djoser

How To Set Up Two-Factor Authentication in cPanel

What is 2FA
Two-Factor Authentication (or 2FA as it often referred to) is an extra layer of security that is used to provide users an additional level of protection when securing access to an account.
Employing a 2FA mechanism is a vast improvement in security over the Singe-Factor Authentication method of simply employing a username and password. Using this method, accounts that have 2FA enabled, require the user to enter a one-time passcode that is generated by an external application. The 2FA passcode (usually a six-digit number) is required to be input into the passcode field before access is granted. The 2FA input is usually required directly after the username and password are entered by the client.

#tutorials #2fa #access #account security #authentication #authentication method #authentication token #cli #command line #cpanel #feature manager #google authenticator #one time password #otp #otp authentication #passcode #password #passwords #qr code #security #security code #security policy #security practices #single factor authentication #time-based one-time password #totp #two factor authentication #whm

Alice Cook

Alice Cook

1615441648

Fix: Gmail Authentication Problems | Gmail 2-step Verification Bypass (2020-21)

An Gmail authentication error occurs when an account’s owner is unable to verify themselves; Gmail perceives it to be a threat to the account and its privacy, so it shows an authentication error. This can occur due to multiple reasons; entering the wrong password, using the wrong server port, and disabled IMAP on Gmail. You will find solutions to fix Gmail authentication problems in this Video. Additionally, you will find ways for Gmail 2-step verification bypass.
Visit: https://contactforhelp.com/gmail/

#gmail authentication error #gmail two factor authentication #gmail 2 step authentication #gmail authentication failed #gmail authentication problems #gmail 2 step verification bypass

Chaz  Homenick

Chaz Homenick

1599056059

Google's Authenticator App Explained and Reviewed

Such a cool-sounding term, I had to find out its meaning and purpose. So here is the story.

Let’s take the story step-wise. You should have heard by now of 2-FA, two-factor authentication. The base idea is pretty simple. Apart from just the password, many of the websites might be sending you an OTP on the phone to grant access. That summarises the two factors. Your password is factor one, and possession of your phone number is factor 2. But just for curious people, I will share some knowledge.

Multi-Factor Authentication

In information security, we have three main pillars to verify someone’s identity.

  • **Knowledge: **Something only the user knows
  • **Possession: **Something only the user has
  • Inherence: Something only the user is

Withdrawing money from ATM checks _possession _of ATM card and knowledge of the PIN. Encashing a cheque checks possession of the cheque book and inherence to the user’s signature. Attendance in my college lectures needs inherence to fingerprint and possession of the ID card. Writing proxy attendance in attendance sheet requires knowledge of friend’s roll number and _inherence _of the fake signature of your friend. You get the idea where it’s going.

Two-Factor authentication, as most of the examples above, is about combining the methods from 2 separate domains. It is different from Two-Step authentication, which can be just a password and a pin, both from the _knowledge _domain.

Where does Google Authenticator come in?

Many secure websites recommend, even enforce you, to use such two factors. More than often, the possession part is your phone number.

But waiting for OTP can be troublesome, especially in a place with poor networking. Many people may be stuck in places that do have good WiFi, internet connectivity but horrible cellular coverage. Like any place in the new CSE building of my college or even Chhatrapati Shivaji Maharaj International Airport in rush hours.

Why so many worries, right? If we just wanted to prove the possession of something, can’t we show the possession of our phone? Something that we always have. And more than often is the device we are using to log in to the website. This is the idea behind Google Authenticator.

How does it work?

At the time of first account creation, if you choose the authenticator app option in the available list, they will provide you with a QR code, which is the main secret that will remain shared between your phone and the website. You should print this QR code and keep it hidden in your cupboard or somewhere you can be safe about. Why? We will come to that later.

Ease of use

This secret that is shared through QR is more than often 16+ length of a random string. So are you supposed to type in every time? That will not only make it tough but also make the string knowledge than possession.

Instead, what the app does for you is taking this secret key and the current time as inputs, it generates a new OTP for you which is a 6–8 digit number that you can type in. This OTP is regenerated in 30 seconds and older OTP expires.

A Cyber hacker has to guess the OTP in a small time window. Anything later than that and the OTP will expire. This will not only prevent the entry but also warn the user through email about his password being compromised.

#two-factor-authentication #multifactor-authentication #google-authenticator #android #password-manager #authentication #technology #hackernoon-top-story

Lymaa Lymaa

Lymaa Lymaa

1621833483

Authenticate With Djoser

REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such as registration, login, logout, password reset and account activation. It works with custom user model.

Requirements:

Project Setup:

create a virtual env.

python -m venv env

Activate
./env/Scripts/activate # for windows

source env/bin/activate # linux user

Here i am using poetry you can use pip or pienv:
poetry Setup:

    poetry init
    poetry add django djangorestframework djoser djangorestframework_simplejwt django-cors-headers
    poetry add drf-yasg # for api docs

Creating project and apps:

    django-admin startproject core
    python manage.py startapp accounts

Configuring settings.py:

# Installed Apps

DJANGO_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]

PROJECT_APPS = ["accounts"]

THIRD_PARTY_APPS = [
"rest_framework",
"drf_yasg",
"djoser",
"corsheaders",
"rest_framework_simplejwt",
"rest_framework_simplejwt.token_blacklist",
]

INSTALLED_APPS = DJANGO_APPS + PROJECT_APPS + THIRD_PARTY_APPS

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware", # middleware for cors-headers
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

let’s create a customuser model:

accounts/models.py

from django.db import models
from django.contrib.auth.models import (
    AbstractBaseUser,
    PermissionsMixin,
    BaseUserManager,
)


class CustomUserManager(BaseUserManager):
    def create_user(self, email, username, password=None, **extra_fields):
        if not email:
            raise ValueError("User must have an email")
        email = self.normalize_email(email)
        user = self.model(email=email, username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email, password=None, **extra_fields):
        user = self.create_user(username, email, password=password, **extra_fields)
        user.is_active = True
        user.is_staff = True
        user.is_admin = True
        user.save(using=self._db)
        return user


class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    username = models.CharField(max_length=255, unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)

    objects = CustomUserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["username", "first_name", "last_name"]

    def get_full_name(self):
        return f"{self.first_name} - {self.last_name}"

    def get_short_name(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    def __str__(self):
        return self.email

Customizing Serializers

accounts/serializers.py

from djoser.serializers import UserCreateSerializer
from django.contrib.auth import get_user_model

User = get_user_model()


class UserCreateSerializer(UserCreateSerializer):
    class Meta(UserCreateSerializer.Meta):
        model = User
        fields = ("id", "email", "username", "first_name", "last_name", "password")

Email setup: settings.py

# EMAIL CONFIG
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "localhost"
EMAIL_PORT = "1025"
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""
EMAIL_USE_TLS = False

Djoser JWT and CORS HEADERS: settings.py

[Note: you won’t need cors header unless you use any frontend framework]

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ),
}


SIMPLE_JWT = {
    "AUTH_HEADER_TYPES": ("JWT",),
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
    "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
}

# DJOSER CONFIG
DJOSER = {
    "LOGIN_FIELD": "email",
    "USER_CREATE_PASSWORD_RETYPE": True,
    "USERNAME_CHANGED_EMAIL_CONFIRMATION": True,
    "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True,
    "SEND_CONFIRMATION_EMAIL": True,
    "SET_USERNAME_RETYPE": True,
    "SET_PASSWORD_RETYPE": True,
    "USERNAME_RESET_CONFIRM_URL": "password/reset/confirm/{uid}/{token}",
    "PASSWORD_RESET_CONFIRM_URL": "email/reset/confirm/{uid}/{token}",
    "ACTIVATION_URL": "activate/{uid}/{token}",
    "SEND_ACTIVATION_EMAIL": True,
    "SOCIAL_AUTH_TOKEN_STRATEGY": "djoser.social.token.jwt.TokenStrategy",
    "SOCIAL_AUTH_ALLOWED_REDIRECT_URIS": [
        "your redirect url",
        "your redirect url",
    ],
    "SERIALIZERS": {
        "user_create": "accounts.serializers.UserCreateSerializer",  # custom serializer
        "user": "djoser.serializers.UserSerializer",
        "current_user": "djoser.serializers.UserSerializer",
        "user_delete": "djoser.serializers.UserSerializer",
    },
}

# CORS HEADERS
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

URL CONFIG:

  • accounts/urls.py
from django.urls import path


urlpatterns = []

  • main/urls.py
#main/urls.py

from django.contrib import admin
from django.urls import path
from django.urls.conf import include, re_path

# DRF YASG
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="Djoser API",
        default_version="v1",
        description="REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such as registration, login, logout, password reset and account activation. It works with custom user model.",
        contact=openapi.Contact(email="contact@snippets.local"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    path("admin/", admin.site.urls),
    re_path(
        r"^api/v1/docs/$",
        schema_view.with_ui("swagger", cache_timeout=0),
        name="schema-swagger-ui",
    ),
    path("api/v1/", include("accounts.urls")),
    path("api/v1/", include("djoser.urls")),
    path("api/v1/", include("djoser.urls.jwt")),
    
]

Here we:

  1. include some url paths that djoser provides us.
  2. and config for API docs
    http://127.0.0.1:8000/api/v1/docs/
    Alt Text
    Api docs

here are some urls:

Requires two parameters:
{
“uid” :“some uid”,
“token”: “some token”
}
postman
Similarly you can work with below apis.

we can work with social-auth too but we require extra configs.
here is the github link where i have work with social auth

overall we are done. 😌😌😌😌
If you are stuck 👇👇👇.


IMAGE ALT TEXT HERE Github


#django #python #djoser #jwt #rest-api #authenticate

I am Developer

1602036957

Laravel 8 REST API Authentication with Passport Example Tutorial

Laravel 8 rest api authentication with passport tutorial, you will learn step by step how to create rest API with laravel 8 passport authentication. And as well as how to install and cofigure passport auth in laravel 8 app.

Laravel 8 API Authentication with Passport Tutorial

Step 1: Download Laravel 8 App
Step 2: Database Configuration
Step 3: Install Passport Auth
Step 4: Passport Configuration
Step 5: Run Migration
Step 6: Create APIs Route
Step 7: Create Passport Auth Controller
Step 8: Now Test Laravel REST API in Postman

https://www.tutsmake.com/laravel-8-rest-api-authentication-with-passport/

#laravel api authentication with passport #laravel 8 api authentication #laravel 8 api authentication token tutorial #laravel 8 api authentication using passport #laravel 8 api authentication session