auth: add tokens.py — HS256 JWT sign/verify helpers
This commit is contained in:
@@ -0,0 +1,28 @@
|
|||||||
|
"""JWT helpers for bincio-auth.
|
||||||
|
|
||||||
|
Tokens are HS256-signed JWTs. Consumers validate locally using the shared
|
||||||
|
secret — no round-trip to the auth service per request.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
import jwt
|
||||||
|
|
||||||
|
|
||||||
|
def create_token(payload: dict, secret: str, expires_in: int) -> str:
|
||||||
|
"""Return a signed JWT.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
payload: Claims to embed (will be shallow-copied; 'exp' is added).
|
||||||
|
secret: HS256 signing key.
|
||||||
|
expires_in: Validity window in seconds from now.
|
||||||
|
"""
|
||||||
|
claims = {**payload, "exp": int(time.time()) + expires_in}
|
||||||
|
return jwt.encode(claims, secret, algorithm="HS256")
|
||||||
|
|
||||||
|
|
||||||
|
def decode_token(token: str, secret: str) -> dict:
|
||||||
|
"""Decode and verify a JWT. Raises jwt.PyJWTError on any failure."""
|
||||||
|
return jwt.decode(token, secret, algorithms=["HS256"])
|
||||||
Reference in New Issue
Block a user