a

authentication

用 bcrypt 進行密碼加密與驗證,支援 salt、自動安全雜湊,保護你的使用者資料不被爆破!適合登入驗證與帳號系統 🚀

0 0 0 1
1 import bcrypt
2
3
4 def encode_password(password: str) -> str:
5 salt = bcrypt.gensalt()
6 hashed = bcrypt.hashpw(password.encode(), salt)
7 return hashed.decode()
8
9
10 def check_password(password: str, hashed: str) -> bool:
Last active 5 hours ago api authentication fastapi header python security

FastAPI 可透過 Header 讀取請求標頭,並透過 Depends 進行依賴注入(Dependency Injection),適用於 API Token 驗證、身份驗證、請求處理 等場景。

0 0 0 3
1 from fastapi import FastAPI, Header, HTTPException
2
3 app = FastAPI()
4
5 @app.get("/secure-data")
6 async def secure_data(api_key: str = Header(None)):
7 if api_key != "my_secure_token":
8 raise HTTPException(status_code=401, detail="無效的 API 金鑰")
9 return {"message": "驗證成功,提供安全數據"}

這段 Python 程式碼使用 JWT(JSON Web Token)來實現 身份驗證與授權。它首先根據 使用者資訊(ID、帳號)及 自訂金鑰 生成一個 有效期限為 30 分鐘 的 JWT,然後透過相同的金鑰來驗證 Token 的有效性,並解碼出原始資料。此機制適用於 使用者登入授權、API 驗證及安全通信,可確保請求的合法性並防止未授權的存取。

0 0 0 1
1 import jwt
2 import datetime
3
4 # 假設的使用者資訊
5 user = {
6 'id': 123,
7 'username': 'exampleUser'
8 }
9
10 # 生成 JWT

此應用程式使用 streamlit_authenticator 進行使用者登入、登出及密碼重設,並支援 YAML 和 JSON 兩種格式作為驗證資料存儲。適用於需要帳戶管理的 Streamlit Web 應用,確保只有授權使用者可以存取內容。

0 0 0 1
1 import json
2 from abc import ABC, abstractmethod
3
4 import streamlit as st
5 import streamlit_authenticator as stauth
6 import yaml
7
8
9 # 策略介面
10 class DataHandlerStrategy(ABC):

這段程式碼使用 Streamlit 和 streamlit-authenticator 來 管理使用者登入,透過 YAML 設定檔 儲存使用者憑證與 Cookie 配置,並提供 登入、登出 和 使用者驗證 功能。

0 0 0 2
1 cookie:
2 expiry_days: 30
3 key: some_signature_key
4 name: my_auth_cookie
5 credentials:
6 usernames:
7 jsmith:
8 email: jsmith@gmail.com
9 failed_login_attempts: 0 # Will be managed automatically
10 logged_in: False # Will be managed automatically

這段程式碼使用 streamlit_authenticator 建立一個簡單的登入系統,支持使用者驗證(帳號、密碼)和登出功能,並在側邊欄提供登出按鈕。密碼經過雜湊處理以增加安全性。

0 0 0 1
1 import streamlit as st # 匯入 streamlit 模組
2 import streamlit_authenticator as stauth # 匯入 streamlit_authenticator 模組
3
4 names = ["John", "Mary"] # 定義名字清單
5 usernames = ["john", "mary"] # 定義使用者名清單
6 passwords = ["1234", "5678"] # 定義密碼清單
7
8 hashed_passwords = stauth.Hasher(passwords).generate() # 使用 Hasher 類別對密碼進行雜湊處理
9
10 authenticator = stauth.Authenticate( # 建立一個 stauth.Authenticate 的實例 authenticator