Django প্রজেক্টে Two-Factor Authentication (2FA) Enable করার সহজ গাইড

pykothon
পাইকথন
Published on Sep, 01 2025 2 min read 1 comments
image

আপনি আপনার Django প্রজেক্টে কি 2 Step Authentication (2FA) enable করতে চান এবং সেটা এমনভাবে যেন আপনি নিজে বেছে নিতে পারেন কোন authentication app (যেমন: Google Authenticator, Authy, Microsoft Authenticator) দিয়ে authenticate করবেন।

 

🔑 Django-তে 2 Step Authentication করার ধাপসমূহ অনুসরণ করতে হবে

1. বেসিক সেটআপ

প্রথমে আপনার Django প্রজেক্টে authentication library লাগবে। এর জন্য সবচেয়ে জনপ্রিয় হলো:

django-otp

django-two-factor-auth (এটা django-otp এর উপর ভিত্তি করে তৈরি)

django-two-factor-auth ব্যবহার করলে authentication apps (Google Authenticator, Authy ইত্যাদি) এর সাথে সহজেই কাজ করে।

pip install django-two-factor-auth qrcode

2. settings.py এ কনফিগারেশন

INSTALLED_APPS = [
    # Default
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 2FA related
    'django_otp',
    'django_otp.plugins.otp_totp',   # Time-based OTP (Google Authenticator compatible)
    'django_otp.plugins.otp_static', # Backup codes
    'two_factor',
    'qrcode',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',

    # OTP middleware
    'django_otp.middleware.OTPMiddleware',

    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

LOGIN_URL = 'two_factor:login' 

3. URL কনফিগারেশন

urls.py এ যোগ করুন:

from django.urls import path, include

urlpatterns = [
    path('', include('two_factor.urls', 'two_factor')),
    path('admin/', admin.site.urls),
]

👉 এতে /account/login/ এর সময় ইউজারনেম+পাসওয়ার্ডের পরে OTP code চাইবে।

4. Authentication App বাছাই করার সুযোগ

যখন কোনো ইউজার তাদের অ্যাকাউন্টে 2FA enable করবে, তখন তারা QR Code পাবে (যেটা scan করলে Google Authenticator / Authy / Microsoft Authenticator – যেকোনোটা ব্যবহার করা যাবে)।

🔹 আপনি ইউজারকে “Choose Your Authentication App” মেসেজ দিতে পারেন।
🔹 বাস্তবে Google Authenticator, Authy, Microsoft Authenticator – সবগুলো একই TOTP standard ফলো করে। 
🔹 মানে ইউজার যেটা ব্যবহার করবে সেটা auto compatible হবে।

5. Optional: Backup Codes

আপনি চাইলে backup codes enable করতে পারেন, যাতে ইউজার OTP device হারালে backup code দিয়ে লগইন করতে পারে। django-two-factor-auth এ এটা বিল্ট-ইন আছে।

শেষ কথা 

এই সেটআপের পর আপনি যা পাবেন -

  • প্রথমে ইউজার Username + Password দিয়ে লগইন করবে।
  • তারপর OTP চাইবে (যা Google Authenticator/Authy/Microsoft Authenticator অ্যাপে জেনারেট হবে)।
  • চাইলে SMS বা Email OTP integrationও করতে পারবেন।
1 Comments