0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

トークン作成関数

0
Posted at

FastAPIにおけるトークン作成

  • 環境変数からSECRET_KEY(秘密鍵ですでに生成済み)を取得
  • 署名アルゴリズムの設定(共通鍵)
  • トークンの期限設定
SECRET_KEY = os.getenv("SECRET_KEY")
ALGORITHM = "HS256"
  • dataのコピーを生成(辞書型はミュータブルのため)
  • 期限の設定
  • to_encode(ユーザ情報)に期限を追加
  • ユーザ情報と期限が合わさったデータをSECRET_KEYALGORITHMで暗号化
  • ランダムになったjwtを返却
def create_access_token(data: dict, expires_delta: timedelta | None = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.now(timezone.utc) + expires_delta
    else:
        expire = datetime.now(timezone.utc) + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?