دمج تدفق كلمات مرور OAuth2
ادمجوا تدفق كلمات مرور OAuth2 لتسجيل دخول المستخدمين والحصول على الرموز المميّزة داخل تطبيق FastAPI.
دمج تدفق كلمات مرور OAuth2 درس مجاني في Node.js Backend Development Bootcamp على CoddyKit. هذا هو الدرس 4 من أصل 6. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Node.js Backend Development Bootcamp، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Node.js Backend Development Bootcamp 6 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Intro to OAuth2 Password Flow
Welcome! This lesson focuses on integrating the OAuth2 Password Flow in FastAPI. It's a standard and secure way for users to log in to your application.
This flow allows users to provide their username and password directly to your API. If successful, your API issues an access token, which the user then uses to access protected resources.
Why Use Password Flow?
The OAuth2 Password Flow is particularly suitable for first-party applications, like your own mobile app or web frontend, where you fully trust the client.
- Security: It's a widely adopted, well-understood security standard.
- Simplicity: Provides a straightforward login experience for users.
- Token-based: After login, users get a token, avoiding the need to send credentials with every request.
Key FastAPI Components
FastAPI provides specialized utilities to make implementing OAuth2 Password Flow easy:
OAuth2PasswordBearer: A dependency that extracts the access token from theAuthorization: Bearerheader of incoming requests.OAuth2PasswordRequestForm: A dependency that automatically parses theusernameandpasswordfrom the form data sent during a login request.
We'll combine these with FastAPI's powerful Dependency Injection system.
Setting up OAuth2PasswordBearer
First, we need to initialize OAuth2PasswordBearer. The tokenUrl parameter is crucial; it tells clients where to send their login credentials to obtain an access token.
This URL will be the path to our login endpoint.
from fastapi import FastAPI
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
# 'token' is the URL path where clients will log in
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# We will create a @app.post("/token") endpoint next!The Login Endpoint: /token
This is the core endpoint where users will send their username and password. It's typically a POST request.
We use OAuth2PasswordRequestForm as a dependency. FastAPI automatically parses the incoming form data and provides username and password attributes.
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
@app.post("/token")
async def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends()
):
# 1. Authenticate user (verify username/password)
# 2. If valid, create an access token
# 3. Return the token
pass # Details coming in the next scene!Full Code: Login & Protected Endpoint
Here's a complete FastAPI application demonstrating the OAuth2 Password Flow. It includes the /token endpoint for login and a /users/me/ endpoint protected by the access token.
Run this code: Save as main.py, then uvicorn main:app --reload. Access docs at http://127.0.0.1:8000/docs.
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# --- Mock User & Token Logic (Simplified for this lesson) ---
class UserInDB(BaseModel):
username: str
hashed_password: str
disabled: Optional[bool] = None
class CurrentUser(BaseModel):
username: str
email: Optional[str] = None
full_name: Optional[str] = None
disabled: Optional[bool] = None
fake_users_db = {
"testuser": UserInDB(username="testuser", hashed_password="password123", disabled=False),
"disableduser": UserInDB(username="disableduser", hashed_password="securepass", disabled=True)
}
def get_user_from_db(username: str):
user_data = fake_users_db.get(username)
if user_data:
return CurrentUser(username=user_data.username, full_name=f"{user_data.username} Full", email=f"{user_data.username}@example.com", disabled=user_data.disabled)
return None
def authenticate_user(username: str, password: str):
user_in_db = fake_users_db.get(username)
if not user_in_db or user_in_db.hashed_password != password: # In real app, use password hashing
return None
return get_user_from_db(username)
def create_access_token(data: dict):
# In a real app, use `jwt.encode` with a secret key (from Lesson 1)
return f"mock_jwt_for_{data['sub']}"
# --- End Mock Logic ---
@app.post("/token")
async def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends()
):
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
if user.disabled:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Inactive user"
)
access_token = create_access_token(data={"sub": user.username})
return {"access_token": access_token, "token_type": "bearer"}
# Dependency to get the current user from the token
async def get_current_user(token: str = Depends(oauth2_scheme)):
# In a real app, this would decode and validate the JWT (from Lesson 1)
if not token.startswith("mock_jwt_for_"):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
username = token.replace("mock_jwt_for_", "")
user = get_user_from_db(username)
if user is None or user.disabled:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials or inactive user",
headers={"WWW-Authenticate": "Bearer"},
)
return user
# A Protected Endpoint
@app.get("/users/me/", response_model=CurrentUser)
async def read_users_me(current_user: CurrentUser = Depends(get_current_user)):
return current_userUnderstanding get_current_user
The get_current_user function is a crucial dependency. It performs two main tasks:
- Extract Token: Uses
oauth2_scheme = Depends(OAuth2PasswordBearer(...))to get the token from theAuthorizationheader. - Validate & Fetch User: Decodes and validates the token (using JWT logic from Lesson 1 in a real app). If valid, it fetches and returns the corresponding
Userobject. If invalid or missing, it raises anHTTPException.
How Clients Interact
Here's a typical client interaction with the OAuth2 Password Flow:
- Client (e.g., mobile app) sends a
POSTrequest to/tokenwith username and password in form data. - If successful, the API returns an
access_token(e.g.,{"access_token": "abc.123.xyz", "token_type": "bearer"}). - For subsequent protected requests, the client includes this token in the
Authorizationheader:Authorization: Bearer abc.123.xyz.
Quick Check: OAuth2 Components
Which FastAPI component is primarily responsible for parsing the username and password from an incoming login request (form data)?
Recap: OAuth2 Password Flow
You've successfully integrated the OAuth2 Password Flow in FastAPI!
- You initialized
OAuth2PasswordBearerwith atokenUrl. - You created a
/tokenendpoint usingOAuth2PasswordRequestFormto handle user login. - You understood how to authenticate users and issue access tokens.
- You secured endpoints by using a
get_current_userdependency to extract and validate the access token.
Next, you can explore Role-Based Access Control (RBAC) to add more granular permissions based on user roles!
الأسئلة الشائعة
هل درس «دمج تدفق كلمات مرور OAuth2» مجاني؟
نعم — نص درس «دمج تدفق كلمات مرور OAuth2» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Node.js Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة Node.js Backend Development Bootcamp 6 دروس في المجموع.
ماذا ستتعلم في «دمج تدفق كلمات مرور OAuth2»؟
ادمجوا تدفق كلمات مرور OAuth2 لتسجيل دخول المستخدمين والحصول على الرموز المميّزة داخل تطبيق FastAPI. تتمرن على Node.js Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Node.js Backend Development Bootcamp؟
لا تُشترط خبرة سابقة. Node.js Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 6.
كم من الوقت يستغرق درس «دمج تدفق كلمات مرور OAuth2»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Node.js Backend Development Bootcamp هذا؟
نعم. كل درس في Node.js Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تسجيل المستخدمين وتسجيل الدخول
- إنشاء رموز JWT والتحقق منها
- JWT للمصادقة عديمة الحالة
- دمج تدفق كلمات مرور OAuth2
- التحكم في الوصول القائم على الأدوار
- التحكم في الوصول المستند إلى الأدوار (RBAC)