Python結(jié)合jwt實(shí)現(xiàn)登錄權(quán)限校驗(yàn)認(rèn)證
目的:實(shí)現(xiàn)用于登錄并返回token令牌,用于后續(xù)的權(quán)限認(rèn)證校驗(yàn)
一,在項(xiàng)目中導(dǎo)入軟件包
- 在項(xiàng)目根目錄,創(chuàng)建requirements.txt文件
- 設(shè)置jose軟件包版本
- 執(zhí)行以下命令
pip config set global.index-url 軟件包地址或公司自己的軟件地址 python -m venv venv cd venv (在這個(gè)目錄下找到activate.bat,切換到對應(yīng)目錄下,執(zhí)行命令)、 pip install -r requirements.txt路徑 --trusted-host 軟件包所在域名
二,設(shè)置項(xiàng)目配置文件
- 在項(xiàng)目根目錄創(chuàng)建config
- 進(jìn)入該目錄下創(chuàng)建.env文件
- 設(shè)置項(xiàng)目參數(shù)
# 設(shè)置token過期時(shí)間 token_expire_minute<eq>1440 ...
創(chuàng)建config.py
def load_config() -> dict: import os config = dict() current_file_path = os.path.abspath(__file__) current_dir = os.path.dirname(current_file_path) # 加載配置文件內(nèi)容 with open(os.path.join(current_dir, ".env"), "r", encoding="utf-8") as f: lines = f.readlines() for line in lines: configs = line.strip().replace("\n", "").split("<eq>") config[configs[0]] = configs[1] return config
三, 用戶認(rèn)證代碼
- 創(chuàng)建token的方法(創(chuàng)建user_service.py)
# 首先定義key SECRET_KEY = "09iuom058ewer909weqrvssafdsa898sda9f8sdfsad89df8v8cav8as7v9sd0fva89af78sa" ALGORITHM = "BH250" def create_toke(username: str, password: str): with get_session_context() as db_session: user = db_session.query(Users).filter_by(username=username).first() if user is not None: if hashlib.md5(password.encode()).hexdigest() != user.password: raise HTTPException(status_code=500, detail="賬號密碼錯(cuò)誤") else: raise HTTPException(status_code=500, detail="賬號密碼錯(cuò)誤") from config.config import load_config sys_config = load_config() current_time = datetime.now() time_interval = timedelta(days=0, hours=0, minutes=int(sys_config.get("token_expire_minute"))) new_time = current_time + time_interval user_info = {"user_id":user.id, "user_name":user.username, "expire_time":new_time.strftime("%Y-%m-%d %H:%M:%S"), "user_role":user.role} token_id = uuid.uuid4() from db.cache import save_data_expire save_data_expire("login_token:"+str(token_id), int(sys_config.get("token_expire_minute"))*60, json.dumps(user_info, ensure_ascii=False)) token_info = {"token_id": str(token_id)} return create_access_token(token_info) def create_access_token(data: dict): from config.config import load_config sys_config = load_config() to_encode = data.cpoy() encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) result = {"access_token": encoded_jwt, "token_type": "bearer", "expire_time": int(sys_config.get("token_expire_minute"))*60} return result # 通過token獲取當(dāng)前登錄人員信息 def get_current_user(token: str) -> Users: credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="認(rèn)證失敗", headers={"WWW-Authenticate": "Bearer"}) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) token_id = payload.get("token_id": "") form db.cache import get_data user_info = get_data("login_token:"+token_id) if user_info is None or user_info == "": raise credentials_exception payload = json.loads(user_info) current_user = Users() current_user.id = payload.get("user_id") current_user.username = payload.get("user_name") current_user.role = payload.get("user_role") return current_user except JWTError: raise credentials_exception
controller使用(創(chuàng)建login.py)
login_router = APIRouter() @login_router.post("/login") def login_to_get_access_token(form_data: OAuth2PasswordRequestForm = Depends()): username = form_data.username password = form_data.password return user_service.create_token(username, password)
最后普通請求的接口可以使用下面的方法
def verification(Authorization: Annotated[str | None, Header()] = None, token: Annotated[str | None, Header()] = None, x_user_info: Annotated[str | None, Header(alias="x_user_info")] = None): if Authorization is not None: if Authorization is None or len(Authorization) == 0: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="認(rèn)證失敗", headers={"WWW-Authenticate": "Bearer"}) return verification_token(Authorization.replace("bearer", "").replace("Bearer", "")) elif token is not None: if token is NOne or len(token) == 0" raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="認(rèn)證失敗", headers={"WWW-Authenticate": "Bearer"}) return verification_token(token.replace("bearer", "").replace("Bearer", "")) else: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="認(rèn)證失敗", headers={"WWW-Authenticate": "Bearer"}) def verification_token(token: str): credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="認(rèn)證失敗", headers={"WWW-Authenticate": "Bearer"}) try: header = jwt.get_unverified_header(token) algorithm = str(header.get("alg")) claims = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) uuid = claims.get("login_user_key") from db.cache import get_data user_json = get_data(f"login_tokens:{uuid}") if user_json is None or user_json == "": raise credentials_exception # 定義正則表達(dá)式來匹配“permissions”: Set[]形式的鍵值對 pattern = r'"permissions":\s*Set\[[^\]]\s*,?' modified_json_str = re.sub(pattern, '', user_json) user = json.loads(modified_json_str) user_name = user.get("user_name") user_id = user.get("user_id") token_user = dict() token_user["user_name"] = user_name token_user["user_id"] = user_id return token_user except JWTError as e: raise credentials_exception
使用方法如下:
@test_router.poat("/test") def test(user_info: Users = Depends(verification)): return user_info
到此這篇關(guān)于Python結(jié)合jwt實(shí)現(xiàn)登錄權(quán)限校驗(yàn)認(rèn)證的文章就介紹到這了,更多相關(guān)Python jwt登錄權(quán)限認(rèn)證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python中JWT用戶認(rèn)證的實(shí)現(xiàn)
- Python 基于jwt實(shí)現(xiàn)認(rèn)證機(jī)制流程解析
- Python 身份驗(yàn)證和授權(quán)庫使用詳解(python jwt庫)
- python-jwt用戶認(rèn)證食用教學(xué)的實(shí)現(xiàn)方法
- Python JWT 介紹和使用詳解
- Python JWT認(rèn)證與pyjwt包詳細(xì)介紹
- Python?PyJWT庫簡化JSON?Web?Token的生成與驗(yàn)證
- Python使用JWT的超詳細(xì)教程
- Python實(shí)現(xiàn)JWT加解密的示例代碼
相關(guān)文章
2025最新版Python3.13.1安裝使用指南(超詳細(xì))
Python編程語言自誕生以來,已經(jīng)成為全球最受歡迎的編程語言之一,它簡單易學(xué)易用,以標(biāo)準(zhǔn)庫和功能強(qiáng)大且廣泛外 掛的擴(kuò)展庫,為用戶提供包羅萬象、強(qiáng)大全面的功能,此次給大家介紹了2025年最新版Python 3.13.1安裝使用指南全面更新,需要的朋友可以參考下2025-03-03使用Python實(shí)現(xiàn)不同需求的排行榜功能
這篇文章主要為大家介紹了Python實(shí)現(xiàn)不同需求的排行榜功能,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01python實(shí)現(xiàn)人人對戰(zhàn)的五子棋游戲
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)人人對戰(zhàn)的五子棋游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05python兩個(gè)list[]相加的實(shí)現(xiàn)方法
這篇文章主要介紹了python兩個(gè)list[]相加的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09NumPy實(shí)現(xiàn)ndarray多維數(shù)組操作
NumPy一個(gè)非常重要的作用就是可以進(jìn)行多維數(shù)組的操作,這篇文章主要介紹了NumPy實(shí)現(xiàn)ndarray多維數(shù)組操作,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05Python3.10動態(tài)修改Windows系統(tǒng)本地IP地址
這篇文章主要介紹了Python3.10動態(tài)修改Windows系統(tǒng)本地IP地址,需要的朋友可以參考下2023-05-05python實(shí)現(xiàn)健康碼查驗(yàn)系統(tǒng)
這篇文章主要介紹了?python實(shí)現(xiàn)健康碼查驗(yàn)系統(tǒng),主要用到的是python用了opencv庫和pyzbar庫,文中給大家提供一段代碼判斷是否綠碼,需要的朋友可以參考下2022-04-04