最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python結(jié)合jwt實(shí)現(xiàn)登錄權(quán)限校驗(yàn)認(rèn)證

 更新時(shí)間:2025年04月28日 09:52:30   作者:沂蒙山旁的水  
本文主要介紹了Python結(jié)合jwt實(shí)現(xiàn)登錄權(quán)限校驗(yàn)認(rèn)證,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

目的:實(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,切換到對(duì)應(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過(guò)期時(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

三, 用戶(hù)認(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="賬號(hào)密碼錯(cuò)誤")
	else:
		raise HTTPException(status_code=500, detail="賬號(hào)密碼錯(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

# 通過(guò)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)

最后普通請(qǐng)求的接口可以使用下面的方法

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á)式來(lái)匹配“permissions”: Set[]形式的鍵值對(duì)
		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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • python實(shí)現(xiàn)dict版圖遍歷示例

    python實(shí)現(xiàn)dict版圖遍歷示例

    這篇文章主要介紹了python實(shí)現(xiàn)dict版圖遍歷的示例,需要的朋友可以參考下
    2014-02-02
  • 幾個(gè)適合python初學(xué)者的簡(jiǎn)單小程序,看完受益匪淺!(推薦)

    幾個(gè)適合python初學(xué)者的簡(jiǎn)單小程序,看完受益匪淺!(推薦)

    這篇文章主要介紹了幾個(gè)適合python初學(xué)者的簡(jiǎn)單小程序,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • 基于Python實(shí)現(xiàn)將列表數(shù)據(jù)生成折線圖

    基于Python實(shí)現(xiàn)將列表數(shù)據(jù)生成折線圖

    這篇文章主要介紹了如何利用Python中的pandas庫(kù)和matplotlib庫(kù),實(shí)現(xiàn)將列表數(shù)據(jù)生成折線圖,文中的示例代碼簡(jiǎn)潔易懂,需要的可以參考一下
    2022-03-03
  • Python pandas之求和運(yùn)算和非空值個(gè)數(shù)統(tǒng)計(jì)

    Python pandas之求和運(yùn)算和非空值個(gè)數(shù)統(tǒng)計(jì)

    數(shù)據(jù)處理的過(guò)程中經(jīng)常會(huì)遇到判斷空值和求和運(yùn)算的需求,所以下面這篇文章主要給大家介紹了關(guān)于Python pandas之求和運(yùn)算和非空值個(gè)數(shù)統(tǒng)計(jì)的相關(guān)資料,需要的朋友可以參考下
    2021-08-08
  • Python selenium文件上傳方法匯總

    Python selenium文件上傳方法匯總

    這篇文章主要為大家詳細(xì)介紹了Python selenium文件上傳方法,selenium文件上傳的所有方法進(jìn)行整理,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • 基于Python實(shí)現(xiàn)新年倒計(jì)時(shí)

    基于Python實(shí)現(xiàn)新年倒計(jì)時(shí)

    眼看馬上春節(jié)就要來(lái)臨了,所以滿(mǎn)懷期待的寫(xiě)了一個(gè)Python新年倒計(jì)時(shí)的小工具!文中的示例代碼簡(jiǎn)潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-01-01
  • python監(jiān)控進(jìn)程狀態(tài),記錄重啟時(shí)間及進(jìn)程號(hào)的實(shí)例

    python監(jiān)控進(jìn)程狀態(tài),記錄重啟時(shí)間及進(jìn)程號(hào)的實(shí)例

    今天小編就為大家分享一篇python監(jiān)控進(jìn)程狀態(tài),記錄重啟時(shí)間及進(jìn)程號(hào)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-07-07
  • 淺析Python的Django框架中的Memcached

    淺析Python的Django框架中的Memcached

    這篇文章主要介紹了淺析Python的Django框架中的緩存機(jī)制,其中著重講到了Memcached,需要的朋友可以參考下
    2015-07-07
  • Python中l(wèi)ambda表達(dá)式的使用詳解(完整通透版)

    Python中l(wèi)ambda表達(dá)式的使用詳解(完整通透版)

    這篇文章主要介紹了Python中l(wèi)ambda表達(dá)式使用的相關(guān)資料,包括其基本語(yǔ)法、常見(jiàn)應(yīng)用場(chǎng)景(如排序、map、filter、reduce函數(shù)結(jié)合使用)以及如何在函數(shù)內(nèi)部或一次性使用,通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-12-12
  • Python如何實(shí)現(xiàn)MySQL實(shí)例初始化詳解

    Python如何實(shí)現(xiàn)MySQL實(shí)例初始化詳解

    這篇文章主要給大家介紹了關(guān)于Python如何實(shí)現(xiàn)MySQL實(shí)例初始化的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-11-11

最新評(píng)論

文水县| 东乡县| 南丹县| 嘉黎县| 驻马店市| 聂荣县| 桑植县| 北碚区| 南澳县| 浦江县| 灌云县| 沾益县| 浮梁县| 云林县| 武陟县| 全椒县| 巴中市| 基隆市| 杂多县| 奉化市| 赞皇县| 兰溪市| 调兵山市| 喀喇沁旗| 武胜县| 班戈县| 花垣县| 都匀市| 玛沁县| 商洛市| 天津市| 和硕县| 东山县| 闵行区| 建湖县| 紫云| 观塘区| 海安县| 鹤峰县| 安溪县| 门源|