Dependency Injection এর মাধ্যমে Authentication এবং Authorization

Web Development - ফাস্টএপিআই (FastAPI) - FastAPI এর Dependency Injection
228

FastAPI তে Dependency Injection ব্যবস্থাপনা অত্যন্ত শক্তিশালী এবং সহজ। এটি Authentication এবং Authorization পরিচালনা করতে ব্যবহৃত হতে পারে, যেখানে আপনি ব্যবহারকারীদের শনাক্ত করতে এবং তাদের অ্যাক্সেস অনুমতি নিয়ন্ত্রণ করতে পারেন।

Dependency Injection (DI) কী?

Dependency Injection (DI) হল একটি ডিজাইন প্যাটার্ন যা অন্য কোনো ক্লাসের বা কম্পোনেন্টের ডিপেনডেন্সি সরবরাহ করে (ইনজেক্ট করে)। FastAPI তে, আপনি এটির মাধ্যমে ফাংশন বা ক্লাসের মধ্যে প্রয়োজনীয় উপাদান সরবরাহ করতে পারেন। Authentication এবং Authorization-এ DI ব্যবহারের মাধ্যমে আপনি নিরাপত্তা যুক্ত করতে পারেন এবং কোডকে আরও মডুলার ও পুনরায় ব্যবহারের উপযোগী করতে পারেন।


Step 1: Dependency Injection এর মাধ্যমে Authentication

Authentication এর উদ্দেশ্য হল ব্যবহারকারীর পরিচয় যাচাই করা (যেমন: username/password দিয়ে লগইন)। FastAPI তে Dependency Injection ব্যবহার করে আপনি এই প্রক্রিয়াকে সহজভাবে ম্যানেজ করতে পারেন।

উদাহরণ: Token-based Authentication

এখানে একটি JWT Token-based Authentication ব্যবস্থার উদাহরণ দেয়া হলো:

from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel
from jose import JWTError, jwt
from datetime import datetime, timedelta
from typing import List

# Secret key for encoding and decoding JWT tokens
SECRET_KEY = "a5e4b5c6d6e6f2e4b9"
ALGORITHM = "HS256"

# FastAPI instance
app = FastAPI()

# User model
class User(BaseModel):
    username: str

# JWT Token schema
class Token(BaseModel):
    access_token: str
    token_type: str

# Dependency to simulate getting a user from a database
def get_user_from_db(username: str):
    if username == "testuser":
        return User(username="testuser")
    return None

# Dependency for authentication (token verification)
def get_current_user(token: str = Depends()):
    credentials_exception = HTTPException(
        status_code=401,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        user = get_user_from_db(username)
        if user is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception
    return user

# Route to generate token (authentication)
@app.post("/token", response_model=Token)
def login_for_access_token(form_data: User):
    user = get_user_from_db(form_data.username)
    if user is None:
        raise HTTPException(
            status_code=404,
            detail="User not found",
        )

    expiration = timedelta(minutes=30)
    access_token_expires = datetime.utcnow() + expiration
    access_token = jwt.encode(
        {"sub": user.username, "exp": access_token_expires},
        SECRET_KEY,
        algorithm=ALGORITHM,
    )

    return {"access_token": access_token, "token_type": "bearer"}

# Protected route using the dependency injection to check the current user
@app.get("/users/me")
def read_users_me(current_user: User = Depends(get_current_user)):
    return {"username": current_user.username}

ব্যাখ্যা:

  • get_current_user: এটি একটি dependency যা JWT token যাচাই করে এবং ভ্যালিড হলে ব্যবহারকারীকে ফেরত দেয়।
  • login_for_access_token: ব্যবহারকারীকে JWT token প্রদান করার জন্য এন্ডপয়েন্ট।
  • read_users_me: এটি একটি প্রটেক্টেড রাউট, যেখানে Depends(get_current_user) দিয়ে রিকোয়েস্টের token যাচাই করা হচ্ছে।

রিকোয়েস্ট উদাহরণ:

  • POST /token: ব্যবহারকারীর নাম এবং পাসওয়ার্ড দিয়ে JWT টোকেন প্রাপ্তি।
{
  "username": "testuser"
}
  • GET /users/me: JWT token হেডারে পাঠানো হলে, বর্তমান লগইন করা ব্যবহারকারী তথ্য ফেরত পাওয়া যাবে।

রেসপন্স:

{
  "username": "testuser"
}

Step 2: Dependency Injection এর মাধ্যমে Authorization

Authorization হল ব্যবহারকারীর বিশেষ অনুমতিগুলি যাচাই করা। FastAPI তে, আপনি Permission-based Authorization সেটআপ করতে পারেন Dependency Injection এর মাধ্যমে। এক্ষেত্রে, আমরা ব্যবহারকারীর ভূমিকা (roles) যাচাই করব।

উদাহরণ: Role-based Authorization

from fastapi import FastAPI, Depends, HTTPException, status
from pydantic import BaseModel

# User model and roles
class User(BaseModel):
    username: str
    role: str

# Simulated database for users
users_db = {
    "admin": {"username": "admin", "role": "admin"},
    "guest": {"username": "guest", "role": "guest"}
}

# Dependency for getting the current user
def get_current_user(username: str):
    user = users_db.get(username)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user

# Dependency for checking if user has the correct role
def get_admin_user(current_user: User = Depends(get_current_user)):
    if current_user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not authorized to access this resource",
        )
    return current_user

# Protected route: Only accessible to 'admin' users
@app.get("/admin/")
def admin_route(current_user: User = Depends(get_admin_user)):
    return {"message": f"Welcome, {current_user.username}, you are an admin."}

ব্যাখ্যা:

  • get_current_user: এই dependency ব্যবহারকারীর নাম দ্বারা ডাটাবেস থেকে ব্যবহারকারী ফেরত দেয়।
  • get_admin_user: এটি একটি authorization dependency যা নিশ্চিত করে যে শুধুমাত্র admin রোলের ব্যবহারকারীই এই রুটটি অ্যাক্সেস করতে পারবে।

রিকোয়েস্ট উদাহরণ:

  • GET /admin/: শুধুমাত্র admin রোলের ব্যবহারকারী অ্যাক্সেস করতে পারবে। যদি guest ব্যবহারকারী এই রুটে প্রবেশের চেষ্টা করে, তাহলে 403 ত্রুটি হবে।

Step 3: Combination of Authentication and Authorization

FastAPI-তে আপনি সহজেই Authentication এবং Authorization একত্রে ব্যবহার করতে পারেন। উপরের উদাহরণগুলোতে আপনি দেখেছেন কিভাবে টোকেন এবং রোল যাচাই করা হয়, এখন একই সময়ে এই দুটোকে একত্রে ব্যবহার করা হবে।

from fastapi import FastAPI, Depends, HTTPException

# Dependency to check if the user has admin privileges
def get_admin_user(current_user: User = Depends(get_current_user)):
    if current_user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not authorized to access this resource",
        )
    return current_user

# Combining authentication and authorization: Admin access
@app.get("/admin/")
def admin_route(current_user: User = Depends(get_admin_user)):
    return {"message": f"Hello {current_user.username}, you are an admin!"}

এখানে:

  • Depends(get_current_user): এই dependency token যাচাই করে ব্যবহারকারীকে ফেরত দেয়।
  • Depends(get_admin_user): এটি ব্যবহৃত হয় authorization চেক করার জন্য।

FastAPI তে Dependency Injection ব্যবহারের মাধ্যমে Authentication এবং Authorization পরিচালনা করা অনেক সহজ এবং পরিষ্কার। আপনি JWT token ব্যবহার করে authentication পরিচালনা করতে পারেন এবং role-based বা permission-based authorization সহ নিরাপদ রাউট তৈরি করতে পারেন। এই প্রক্রিয়া FastAPI কে আরও শক্তিশালী এবং নিরাপদ API ডেভেলপমেন্টের জন্য উপযোগী করে তোলে।

Content added By
Promotion
NEW SATT AI এখন আপনাকে সাহায্য করতে পারে।

Are you sure to start over?

Loading...