jwt-sessions 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jwt_sessions/__init__.py +24 -0
- jwt_sessions/core.py +96 -0
- jwt_sessions/fastapi.py +189 -0
- jwt_sessions/memory.py +77 -0
- jwt_sessions/passwords.py +40 -0
- jwt_sessions/refresh.py +152 -0
- jwt_sessions/sqlalchemy_store.py +174 -0
- jwt_sessions/tokens.py +88 -0
- jwt_sessions-0.1.0.dist-info/METADATA +133 -0
- jwt_sessions-0.1.0.dist-info/RECORD +12 -0
- jwt_sessions-0.1.0.dist-info/WHEEL +4 -0
- jwt_sessions-0.1.0.dist-info/licenses/LICENSE +21 -0
jwt_sessions/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""First-party JWT auth with rotating, reuse-detecting refresh tokens."""
|
|
2
|
+
|
|
3
|
+
from jwt_sessions.core import Auth, AuthUser, InvalidCredentials, Session, UserStore
|
|
4
|
+
from jwt_sessions.memory import InMemoryRefreshStore
|
|
5
|
+
from jwt_sessions.passwords import check_password, hash_password, needs_rehash
|
|
6
|
+
from jwt_sessions.refresh import RefreshRejected, RefreshStore, RefreshTokens
|
|
7
|
+
from jwt_sessions.tokens import AccessTokens, InvalidToken
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"AccessTokens",
|
|
11
|
+
"Auth",
|
|
12
|
+
"AuthUser",
|
|
13
|
+
"InMemoryRefreshStore",
|
|
14
|
+
"InvalidCredentials",
|
|
15
|
+
"InvalidToken",
|
|
16
|
+
"RefreshRejected",
|
|
17
|
+
"RefreshStore",
|
|
18
|
+
"RefreshTokens",
|
|
19
|
+
"Session",
|
|
20
|
+
"UserStore",
|
|
21
|
+
"check_password",
|
|
22
|
+
"hash_password",
|
|
23
|
+
"needs_rehash",
|
|
24
|
+
]
|
jwt_sessions/core.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""The session lifecycle: sign in, refresh, sign out - in terms of the two
|
|
2
|
+
things an application supplies, where its users are (`UserStore`) and where
|
|
3
|
+
refresh tokens are kept (`RefreshStore`).
|
|
4
|
+
|
|
5
|
+
Framework-free; `jwt_sessions.fastapi` puts it behind HTTP.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
from typing import Any, Protocol
|
|
14
|
+
|
|
15
|
+
from jwt_sessions.passwords import check_password
|
|
16
|
+
from jwt_sessions.refresh import RefreshRejected, RefreshTokens
|
|
17
|
+
from jwt_sessions.tokens import AccessTokens
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class AuthUser:
|
|
22
|
+
"""What the library needs to know about a user."""
|
|
23
|
+
|
|
24
|
+
id: str
|
|
25
|
+
password_hash: str
|
|
26
|
+
active: bool = True
|
|
27
|
+
#: Extra claims for the access token - a role, say. Read again on every
|
|
28
|
+
#: refresh, so a changed role reaches the token within one access TTL.
|
|
29
|
+
claims: Mapping[str, Any] = field(default_factory=dict)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class UserStore(Protocol):
|
|
33
|
+
async def by_login(self, login: str) -> AuthUser | None:
|
|
34
|
+
"""The user signing in as `login` (an email, usually). Normalise case
|
|
35
|
+
here if logins are case-insensitive."""
|
|
36
|
+
...
|
|
37
|
+
|
|
38
|
+
async def by_id(self, user_id: str) -> AuthUser | None: ...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class InvalidCredentials(Exception):
|
|
42
|
+
"""Wrong login or password, or an inactive account - deliberately one
|
|
43
|
+
error, so the response does not say which."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Session:
|
|
48
|
+
access_token: str
|
|
49
|
+
refresh_token: str
|
|
50
|
+
user_id: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class Auth:
|
|
55
|
+
users: UserStore
|
|
56
|
+
access: AccessTokens
|
|
57
|
+
refresh: RefreshTokens
|
|
58
|
+
|
|
59
|
+
async def login(
|
|
60
|
+
self, login: str, password: str, *, now: datetime | None = None
|
|
61
|
+
) -> Session:
|
|
62
|
+
user = await self.users.by_login(login)
|
|
63
|
+
# Always one argon2 verification, account or not - see passwords.py.
|
|
64
|
+
ok = check_password(password, user.password_hash if user else None)
|
|
65
|
+
if user is None or not ok or not user.active:
|
|
66
|
+
raise InvalidCredentials
|
|
67
|
+
refresh_token = await self.refresh.start(user.id, now=now)
|
|
68
|
+
return Session(
|
|
69
|
+
access_token=self.access.issue(user.id, user.claims, now=now),
|
|
70
|
+
refresh_token=refresh_token,
|
|
71
|
+
user_id=user.id,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
async def renew(
|
|
75
|
+
self, refresh_token: str, *, now: datetime | None = None
|
|
76
|
+
) -> Session:
|
|
77
|
+
"""A new access token and the refresh token's successor; RefreshRejected
|
|
78
|
+
otherwise. An account deactivated since sign-in ends the session."""
|
|
79
|
+
rotated = await self.refresh.rotate(refresh_token, now=now)
|
|
80
|
+
user = await self.users.by_id(rotated.user_id)
|
|
81
|
+
if user is None or not user.active:
|
|
82
|
+
await self.refresh.revoke(rotated.token, now=now)
|
|
83
|
+
raise RefreshRejected("inactive")
|
|
84
|
+
return Session(
|
|
85
|
+
access_token=self.access.issue(user.id, user.claims, now=now),
|
|
86
|
+
refresh_token=rotated.token,
|
|
87
|
+
user_id=user.id,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
async def logout(self, refresh_token: str, *, now: datetime | None = None) -> None:
|
|
91
|
+
await self.refresh.revoke(refresh_token, now=now)
|
|
92
|
+
|
|
93
|
+
async def logout_everywhere(
|
|
94
|
+
self, user_id: str, *, now: datetime | None = None
|
|
95
|
+
) -> int:
|
|
96
|
+
return await self.refresh.revoke_user(user_id, now=now)
|
jwt_sessions/fastapi.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""The HTTP contract, for FastAPI.
|
|
2
|
+
|
|
3
|
+
POST {prefix}/login {"email", "password"} -> {"access_token"}
|
|
4
|
+
+ Set-Cookie: the refresh token (httpOnly)
|
|
5
|
+
POST {prefix}/refresh cookie -> {"access_token"} + the rotated cookie
|
|
6
|
+
POST {prefix}/logout cookie -> 204; session revoked, cookie cleared
|
|
7
|
+
POST {prefix}/logout-all Bearer -> 204; every session of the user revoked
|
|
8
|
+
|
|
9
|
+
The refresh token only ever travels in an httpOnly cookie - never in a body
|
|
10
|
+
JavaScript can read - and the access token only in response bodies and the
|
|
11
|
+
Authorization header, never in a cookie, so no request is authorised by a
|
|
12
|
+
cookie alone. The refresh cookie is SameSite=Lax by default: a cross-site
|
|
13
|
+
POST does not carry it, and nothing a cross-site page could make the
|
|
14
|
+
browser send gets it an access token it could read.
|
|
15
|
+
|
|
16
|
+
What a browser client has to do is in the README ("What a client has to
|
|
17
|
+
do"); there is no client library.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from collections.abc import Awaitable, Callable
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from typing import Any, Literal
|
|
25
|
+
|
|
26
|
+
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
|
27
|
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
28
|
+
from pydantic import BaseModel, Field
|
|
29
|
+
|
|
30
|
+
from jwt_sessions.core import Auth, InvalidCredentials
|
|
31
|
+
from jwt_sessions.refresh import RefreshRejected
|
|
32
|
+
from jwt_sessions.tokens import InvalidToken
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class CookieSettings:
|
|
37
|
+
name: str = "refresh_token"
|
|
38
|
+
#: None: the directory the auth endpoints are served from, worked out
|
|
39
|
+
#: per request, so the cookie goes only to them wherever the router is
|
|
40
|
+
#: mounted. Set it when the app sits behind a proxy that rewrites paths.
|
|
41
|
+
path: str | None = None
|
|
42
|
+
#: Off only for local development over plain HTTP.
|
|
43
|
+
secure: bool = True
|
|
44
|
+
samesite: Literal["lax", "strict", "none"] = "lax"
|
|
45
|
+
domain: str | None = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class LoginBody(BaseModel):
|
|
49
|
+
email: str = Field(min_length=1, max_length=320)
|
|
50
|
+
# Bounded: argon2 hashes whatever it is given, and a megabyte password
|
|
51
|
+
# is a cheap way to make a server do expensive work.
|
|
52
|
+
password: str = Field(min_length=1, max_length=1024)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class AccessTokenResponse(BaseModel):
|
|
56
|
+
access_token: str
|
|
57
|
+
token_type: Literal["bearer"] = "bearer" # noqa: S105 - a scheme name
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _unauthorized(detail: str) -> HTTPException:
|
|
61
|
+
return HTTPException(
|
|
62
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
63
|
+
detail=detail,
|
|
64
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def bearer_claims(auth: Auth) -> Callable[..., Awaitable[dict[str, Any]]]:
|
|
69
|
+
"""A dependency: the verified claims of the request's access token, or
|
|
70
|
+
401. Loading the application's own user from `claims["sub"]` - and
|
|
71
|
+
checking it is still allowed in - is the application's business."""
|
|
72
|
+
scheme = HTTPBearer(auto_error=False)
|
|
73
|
+
|
|
74
|
+
async def dependency(
|
|
75
|
+
credentials: HTTPAuthorizationCredentials | None = Depends(scheme),
|
|
76
|
+
) -> dict[str, Any]:
|
|
77
|
+
if credentials is None:
|
|
78
|
+
raise _unauthorized("Not authenticated")
|
|
79
|
+
try:
|
|
80
|
+
return auth.access.verify(credentials.credentials)
|
|
81
|
+
except InvalidToken as exc:
|
|
82
|
+
raise _unauthorized("Invalid or expired access token") from exc
|
|
83
|
+
|
|
84
|
+
return dependency
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def auth_router(
|
|
88
|
+
auth: Auth,
|
|
89
|
+
*,
|
|
90
|
+
cookie: CookieSettings | None = None,
|
|
91
|
+
prefix: str = "/auth",
|
|
92
|
+
) -> APIRouter:
|
|
93
|
+
cookie = cookie or CookieSettings()
|
|
94
|
+
router = APIRouter(prefix=prefix, tags=["auth"])
|
|
95
|
+
current_claims = bearer_claims(auth)
|
|
96
|
+
|
|
97
|
+
def cookie_path(request: Request) -> str:
|
|
98
|
+
if cookie.path is not None:
|
|
99
|
+
return cookie.path
|
|
100
|
+
return request.url.path.rsplit("/", 1)[0] or "/"
|
|
101
|
+
|
|
102
|
+
def set_cookie(request: Request, response: Response, token: str) -> None:
|
|
103
|
+
response.set_cookie(
|
|
104
|
+
key=cookie.name,
|
|
105
|
+
value=token,
|
|
106
|
+
max_age=auth.refresh.ttl_seconds,
|
|
107
|
+
path=cookie_path(request),
|
|
108
|
+
domain=cookie.domain,
|
|
109
|
+
secure=cookie.secure,
|
|
110
|
+
httponly=True,
|
|
111
|
+
samesite=cookie.samesite,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
def clear_cookie(request: Request, response: Response) -> None:
|
|
115
|
+
response.delete_cookie(
|
|
116
|
+
key=cookie.name,
|
|
117
|
+
path=cookie_path(request),
|
|
118
|
+
domain=cookie.domain,
|
|
119
|
+
secure=cookie.secure,
|
|
120
|
+
httponly=True,
|
|
121
|
+
samesite=cookie.samesite,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
@router.post("/login", response_model=AccessTokenResponse)
|
|
125
|
+
async def login(
|
|
126
|
+
body: LoginBody, request: Request, response: Response
|
|
127
|
+
) -> AccessTokenResponse:
|
|
128
|
+
try:
|
|
129
|
+
session = await auth.login(body.email, body.password)
|
|
130
|
+
except InvalidCredentials as exc:
|
|
131
|
+
raise _unauthorized("Invalid email or password") from exc
|
|
132
|
+
set_cookie(request, response, session.refresh_token)
|
|
133
|
+
return AccessTokenResponse(access_token=session.access_token)
|
|
134
|
+
|
|
135
|
+
@router.post("/refresh", response_model=AccessTokenResponse)
|
|
136
|
+
async def refresh(request: Request, response: Response) -> AccessTokenResponse:
|
|
137
|
+
token = request.cookies.get(cookie.name)
|
|
138
|
+
if not token:
|
|
139
|
+
raise _unauthorized("Missing refresh token")
|
|
140
|
+
try:
|
|
141
|
+
session = await auth.renew(token)
|
|
142
|
+
except RefreshRejected as exc:
|
|
143
|
+
# The cookie is dead either way; a 401 carries no Set-Cookie
|
|
144
|
+
# unless it is attached to the exception.
|
|
145
|
+
raise HTTPException(
|
|
146
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
147
|
+
detail="Session expired - sign in again",
|
|
148
|
+
headers={
|
|
149
|
+
"WWW-Authenticate": "Bearer",
|
|
150
|
+
"Set-Cookie": _expired_cookie_header(cookie, cookie_path(request)),
|
|
151
|
+
},
|
|
152
|
+
) from exc
|
|
153
|
+
set_cookie(request, response, session.refresh_token)
|
|
154
|
+
return AccessTokenResponse(access_token=session.access_token)
|
|
155
|
+
|
|
156
|
+
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
157
|
+
async def logout(request: Request, response: Response) -> None:
|
|
158
|
+
token = request.cookies.get(cookie.name)
|
|
159
|
+
if token:
|
|
160
|
+
await auth.logout(token)
|
|
161
|
+
clear_cookie(request, response)
|
|
162
|
+
|
|
163
|
+
@router.post(
|
|
164
|
+
"/logout-all", status_code=status.HTTP_204_NO_CONTENT, response_model=None
|
|
165
|
+
)
|
|
166
|
+
async def logout_all(
|
|
167
|
+
request: Request,
|
|
168
|
+
response: Response,
|
|
169
|
+
claims: dict[str, Any] = Depends(current_claims),
|
|
170
|
+
) -> None:
|
|
171
|
+
await auth.logout_everywhere(str(claims["sub"]))
|
|
172
|
+
clear_cookie(request, response)
|
|
173
|
+
|
|
174
|
+
return router
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _expired_cookie_header(cookie: CookieSettings, path: str) -> str:
|
|
178
|
+
parts = [
|
|
179
|
+
f'{cookie.name}=""',
|
|
180
|
+
"Max-Age=0",
|
|
181
|
+
f"Path={path}",
|
|
182
|
+
"HttpOnly",
|
|
183
|
+
f"SameSite={cookie.samesite}",
|
|
184
|
+
]
|
|
185
|
+
if cookie.secure:
|
|
186
|
+
parts.append("Secure")
|
|
187
|
+
if cookie.domain:
|
|
188
|
+
parts.append(f"Domain={cookie.domain}")
|
|
189
|
+
return "; ".join(parts)
|
jwt_sessions/memory.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""An in-memory `RefreshStore` - for tests and single-process demos. A
|
|
2
|
+
restart signs everyone out."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
from dataclasses import dataclass, replace
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
|
|
10
|
+
from jwt_sessions.refresh import RefreshRecord
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class _Family:
|
|
15
|
+
user_id: str
|
|
16
|
+
revoked_at: datetime | None = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class InMemoryRefreshStore:
|
|
20
|
+
def __init__(self) -> None:
|
|
21
|
+
self._families: dict[str, _Family] = {}
|
|
22
|
+
self._tokens: dict[str, RefreshRecord] = {}
|
|
23
|
+
self._lock = asyncio.Lock()
|
|
24
|
+
|
|
25
|
+
async def create_family(self, family_id: str, user_id: str, at: datetime) -> None:
|
|
26
|
+
self._families[family_id] = _Family(user_id=user_id)
|
|
27
|
+
|
|
28
|
+
async def add_token(
|
|
29
|
+
self, token_hash: str, family_id: str, issued_at: datetime, expires_at: datetime
|
|
30
|
+
) -> None:
|
|
31
|
+
family = self._families[family_id]
|
|
32
|
+
self._tokens[token_hash] = RefreshRecord(
|
|
33
|
+
token_hash=token_hash,
|
|
34
|
+
family_id=family_id,
|
|
35
|
+
user_id=family.user_id,
|
|
36
|
+
issued_at=issued_at,
|
|
37
|
+
expires_at=expires_at,
|
|
38
|
+
used_at=None,
|
|
39
|
+
family_revoked_at=None,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
async def get(self, token_hash: str) -> RefreshRecord | None:
|
|
43
|
+
record = self._tokens.get(token_hash)
|
|
44
|
+
if record is None:
|
|
45
|
+
return None
|
|
46
|
+
return replace(
|
|
47
|
+
record, family_revoked_at=self._families[record.family_id].revoked_at
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
async def mark_used(self, token_hash: str, at: datetime) -> bool:
|
|
51
|
+
async with self._lock:
|
|
52
|
+
record = self._tokens.get(token_hash)
|
|
53
|
+
if record is None or record.used_at is not None:
|
|
54
|
+
return False
|
|
55
|
+
self._tokens[token_hash] = replace(record, used_at=at)
|
|
56
|
+
return True
|
|
57
|
+
|
|
58
|
+
async def revoke_family(self, family_id: str, at: datetime) -> None:
|
|
59
|
+
family = self._families.get(family_id)
|
|
60
|
+
if family is not None and family.revoked_at is None:
|
|
61
|
+
family.revoked_at = at
|
|
62
|
+
|
|
63
|
+
async def revoke_user(self, user_id: str, at: datetime) -> int:
|
|
64
|
+
live = [
|
|
65
|
+
f
|
|
66
|
+
for f in self._families.values()
|
|
67
|
+
if f.user_id == user_id and f.revoked_at is None
|
|
68
|
+
]
|
|
69
|
+
for family in live:
|
|
70
|
+
family.revoked_at = at
|
|
71
|
+
return len(live)
|
|
72
|
+
|
|
73
|
+
async def purge(self, before: datetime) -> int:
|
|
74
|
+
stale = [h for h, r in self._tokens.items() if r.expires_at < before]
|
|
75
|
+
for h in stale:
|
|
76
|
+
del self._tokens[h]
|
|
77
|
+
return len(stale)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Password hashing: argon2id through pwdlib, and a login check that takes
|
|
2
|
+
the same time whether or not the account exists.
|
|
3
|
+
|
|
4
|
+
The platform this was extracted from answered an unknown email without
|
|
5
|
+
hashing anything, so "no such account" came back measurably faster than
|
|
6
|
+
"wrong password" - which tells anyone timing the endpoint which addresses
|
|
7
|
+
have accounts. `check_password` always runs one argon2 verification.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import secrets
|
|
13
|
+
|
|
14
|
+
from pwdlib import PasswordHash
|
|
15
|
+
|
|
16
|
+
_hasher = PasswordHash.recommended()
|
|
17
|
+
|
|
18
|
+
# Verified against when there is no account, so both paths cost one argon2
|
|
19
|
+
# verification. It matches no password anyone sends (it is the hash of a
|
|
20
|
+
# random value discarded at import).
|
|
21
|
+
_DUMMY_HASH = _hasher.hash(secrets.token_urlsafe(32))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def hash_password(password: str) -> str:
|
|
25
|
+
return _hasher.hash(password)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def check_password(password: str, hashed: str | None) -> bool:
|
|
29
|
+
"""Whether `password` matches `hashed`; `hashed` is None when there is
|
|
30
|
+
no such account, and the answer is then False after the same work."""
|
|
31
|
+
if hashed is None:
|
|
32
|
+
_hasher.verify(password, _DUMMY_HASH)
|
|
33
|
+
return False
|
|
34
|
+
return _hasher.verify(password, hashed)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def needs_rehash(hashed: str) -> bool:
|
|
38
|
+
"""True when `hashed` was made with weaker parameters than today's
|
|
39
|
+
defaults - rehash it on the next successful login."""
|
|
40
|
+
return _hasher.current_hasher.check_needs_rehash(hashed)
|
jwt_sessions/refresh.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Refresh tokens: opaque, rotated on every use, and grouped into families
|
|
2
|
+
so that a stolen one gives itself away.
|
|
3
|
+
|
|
4
|
+
A login starts a **family**. Every refresh spends the presented token and
|
|
5
|
+
issues its successor in the same family. A token presented a second time
|
|
6
|
+
means two parties hold it - the user and whoever copied it - and there is
|
|
7
|
+
no telling which is which, so the whole family is revoked: both are signed
|
|
8
|
+
out, and the thief's copy is dead. (A stateless refresh JWT, which is what
|
|
9
|
+
this replaces, cannot do any of that: a copied one keeps working until it
|
|
10
|
+
expires, however often the real user refreshes.)
|
|
11
|
+
|
|
12
|
+
One exception, `reuse_grace_seconds`: two tabs of the same browser that
|
|
13
|
+
refresh at the same moment both send the token the cookie held, and the
|
|
14
|
+
second arrives already spent. Within the grace window a spent token gets a
|
|
15
|
+
successor instead of revoking the family. It is a window a thief could use
|
|
16
|
+
too, if they replay within those seconds of the real refresh; the default
|
|
17
|
+
is 10 s, and 0 turns it off.
|
|
18
|
+
|
|
19
|
+
Tokens are random, not JWTs, and only their SHA-256 is stored, so a leaked
|
|
20
|
+
table holds nothing that can be presented.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import hashlib
|
|
26
|
+
import secrets
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from datetime import UTC, datetime, timedelta
|
|
29
|
+
from typing import Protocol
|
|
30
|
+
from uuid import uuid4
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def token_hash(token: str) -> str:
|
|
34
|
+
return hashlib.sha256(token.encode()).hexdigest()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class RefreshRecord:
|
|
39
|
+
"""One refresh token as stored, with its family's state."""
|
|
40
|
+
|
|
41
|
+
token_hash: str
|
|
42
|
+
family_id: str
|
|
43
|
+
user_id: str
|
|
44
|
+
issued_at: datetime
|
|
45
|
+
expires_at: datetime
|
|
46
|
+
used_at: datetime | None
|
|
47
|
+
#: When the family was revoked - logout, reuse, or revoke-all.
|
|
48
|
+
family_revoked_at: datetime | None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class RefreshStore(Protocol):
|
|
52
|
+
"""Where families and tokens live. `mark_used` must be atomic: of two
|
|
53
|
+
concurrent calls for the same token, exactly one returns True."""
|
|
54
|
+
|
|
55
|
+
async def create_family(
|
|
56
|
+
self, family_id: str, user_id: str, at: datetime
|
|
57
|
+
) -> None: ...
|
|
58
|
+
|
|
59
|
+
async def add_token(
|
|
60
|
+
self, token_hash: str, family_id: str, issued_at: datetime, expires_at: datetime
|
|
61
|
+
) -> None: ...
|
|
62
|
+
|
|
63
|
+
async def get(self, token_hash: str) -> RefreshRecord | None: ...
|
|
64
|
+
|
|
65
|
+
async def mark_used(self, token_hash: str, at: datetime) -> bool: ...
|
|
66
|
+
|
|
67
|
+
async def revoke_family(self, family_id: str, at: datetime) -> None: ...
|
|
68
|
+
|
|
69
|
+
async def revoke_user(self, user_id: str, at: datetime) -> int:
|
|
70
|
+
"""Revoke every live family of the user; how many there were."""
|
|
71
|
+
...
|
|
72
|
+
|
|
73
|
+
async def purge(self, before: datetime) -> int:
|
|
74
|
+
"""Drop tokens that expired before `before`; how many."""
|
|
75
|
+
...
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class RefreshRejected(Exception):
|
|
79
|
+
"""The refresh token cannot be used. `reason` is one of "unknown",
|
|
80
|
+
"expired", "revoked" and "reused" - for logs; a client is told only
|
|
81
|
+
that it must sign in again."""
|
|
82
|
+
|
|
83
|
+
def __init__(self, reason: str) -> None:
|
|
84
|
+
super().__init__(reason)
|
|
85
|
+
self.reason = reason
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class Rotated:
|
|
90
|
+
token: str
|
|
91
|
+
user_id: str
|
|
92
|
+
family_id: str
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class RefreshTokens:
|
|
97
|
+
store: RefreshStore
|
|
98
|
+
ttl_seconds: int = 30 * 24 * 3600
|
|
99
|
+
reuse_grace_seconds: int = 10
|
|
100
|
+
|
|
101
|
+
async def start(self, user_id: str, *, now: datetime | None = None) -> str:
|
|
102
|
+
"""A new family for a fresh login, and its first token."""
|
|
103
|
+
now = now or datetime.now(UTC)
|
|
104
|
+
family_id = uuid4().hex
|
|
105
|
+
await self.store.create_family(family_id, user_id, now)
|
|
106
|
+
return await self._issue(family_id, now)
|
|
107
|
+
|
|
108
|
+
async def rotate(self, token: str, *, now: datetime | None = None) -> Rotated:
|
|
109
|
+
"""Spend `token` and return its successor - or RefreshRejected, having
|
|
110
|
+
revoked the family if the token had already been spent."""
|
|
111
|
+
now = now or datetime.now(UTC)
|
|
112
|
+
record = await self.store.get(token_hash(token))
|
|
113
|
+
if record is None:
|
|
114
|
+
raise RefreshRejected("unknown")
|
|
115
|
+
if record.family_revoked_at is not None:
|
|
116
|
+
raise RefreshRejected("revoked")
|
|
117
|
+
if record.expires_at <= now:
|
|
118
|
+
raise RefreshRejected("expired")
|
|
119
|
+
if not await self.store.mark_used(record.token_hash, now):
|
|
120
|
+
spent = await self.store.get(record.token_hash)
|
|
121
|
+
used_at = spent.used_at if spent else None
|
|
122
|
+
within_grace = (
|
|
123
|
+
used_at is not None
|
|
124
|
+
and self.reuse_grace_seconds > 0
|
|
125
|
+
and now - used_at <= timedelta(seconds=self.reuse_grace_seconds)
|
|
126
|
+
)
|
|
127
|
+
if not within_grace:
|
|
128
|
+
await self.store.revoke_family(record.family_id, now)
|
|
129
|
+
raise RefreshRejected("reused")
|
|
130
|
+
successor = await self._issue(record.family_id, now)
|
|
131
|
+
return Rotated(
|
|
132
|
+
token=successor, user_id=record.user_id, family_id=record.family_id
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
async def revoke(self, token: str, *, now: datetime | None = None) -> None:
|
|
136
|
+
"""End the session `token` belongs to (sign-out). Unknown tokens are
|
|
137
|
+
ignored: signing out twice is not an error."""
|
|
138
|
+
record = await self.store.get(token_hash(token))
|
|
139
|
+
if record is not None:
|
|
140
|
+
await self.store.revoke_family(record.family_id, now or datetime.now(UTC))
|
|
141
|
+
|
|
142
|
+
async def revoke_user(self, user_id: str, *, now: datetime | None = None) -> int:
|
|
143
|
+
"""End every session of the user - sign out everywhere, a password
|
|
144
|
+
change, a deactivated account."""
|
|
145
|
+
return await self.store.revoke_user(user_id, now or datetime.now(UTC))
|
|
146
|
+
|
|
147
|
+
async def _issue(self, family_id: str, now: datetime) -> str:
|
|
148
|
+
token = secrets.token_urlsafe(32)
|
|
149
|
+
await self.store.add_token(
|
|
150
|
+
token_hash(token), family_id, now, now + timedelta(seconds=self.ttl_seconds)
|
|
151
|
+
)
|
|
152
|
+
return token
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""A `RefreshStore` on SQLAlchemy (async), for any database it supports.
|
|
2
|
+
|
|
3
|
+
The tables are defined on the application's own `MetaData`, so its
|
|
4
|
+
migrations (Alembic autogenerate included) see them like any other table:
|
|
5
|
+
|
|
6
|
+
families, tokens = refresh_tables(Base.metadata)
|
|
7
|
+
store = SQLAlchemyRefreshStore(async_sessionmaker(engine), families, tokens)
|
|
8
|
+
|
|
9
|
+
`mark_used` is a conditional UPDATE (`... WHERE used_at IS NULL`), which is
|
|
10
|
+
what makes it atomic: of two concurrent refreshes with the same token,
|
|
11
|
+
exactly one changes a row.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from datetime import UTC, datetime
|
|
17
|
+
|
|
18
|
+
from sqlalchemy import (
|
|
19
|
+
Column,
|
|
20
|
+
DateTime,
|
|
21
|
+
ForeignKey,
|
|
22
|
+
Index,
|
|
23
|
+
MetaData,
|
|
24
|
+
String,
|
|
25
|
+
Table,
|
|
26
|
+
delete,
|
|
27
|
+
select,
|
|
28
|
+
update,
|
|
29
|
+
)
|
|
30
|
+
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
|
31
|
+
|
|
32
|
+
from jwt_sessions.refresh import RefreshRecord
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def refresh_tables(metadata: MetaData, prefix: str = "auth_") -> tuple[Table, Table]:
|
|
36
|
+
families = Table(
|
|
37
|
+
f"{prefix}refresh_families",
|
|
38
|
+
metadata,
|
|
39
|
+
Column("id", String(32), primary_key=True),
|
|
40
|
+
Column("user_id", String(64), nullable=False),
|
|
41
|
+
Column("created_at", DateTime(timezone=True), nullable=False),
|
|
42
|
+
Column("revoked_at", DateTime(timezone=True), nullable=True),
|
|
43
|
+
Index(f"ix_{prefix}refresh_families_user_id", "user_id"),
|
|
44
|
+
)
|
|
45
|
+
tokens = Table(
|
|
46
|
+
f"{prefix}refresh_tokens",
|
|
47
|
+
metadata,
|
|
48
|
+
# SHA-256 of the token, hex. The token itself is never stored.
|
|
49
|
+
Column("token_hash", String(64), primary_key=True),
|
|
50
|
+
Column(
|
|
51
|
+
"family_id",
|
|
52
|
+
String(32),
|
|
53
|
+
ForeignKey(families.c.id, ondelete="CASCADE"),
|
|
54
|
+
nullable=False,
|
|
55
|
+
),
|
|
56
|
+
Column("issued_at", DateTime(timezone=True), nullable=False),
|
|
57
|
+
Column("expires_at", DateTime(timezone=True), nullable=False),
|
|
58
|
+
Column("used_at", DateTime(timezone=True), nullable=True),
|
|
59
|
+
Index(f"ix_{prefix}refresh_tokens_family_id", "family_id"),
|
|
60
|
+
Index(f"ix_{prefix}refresh_tokens_expires_at", "expires_at"),
|
|
61
|
+
)
|
|
62
|
+
return families, tokens
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _aware(value: datetime | None) -> datetime | None:
|
|
66
|
+
# SQLite hands timezone-aware columns back naive; they were written UTC.
|
|
67
|
+
if value is not None and value.tzinfo is None:
|
|
68
|
+
return value.replace(tzinfo=UTC)
|
|
69
|
+
return value
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class SQLAlchemyRefreshStore:
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
sessions: async_sessionmaker[AsyncSession],
|
|
76
|
+
families: Table,
|
|
77
|
+
tokens: Table,
|
|
78
|
+
) -> None:
|
|
79
|
+
self._sessions = sessions
|
|
80
|
+
self._families = families
|
|
81
|
+
self._tokens = tokens
|
|
82
|
+
|
|
83
|
+
async def create_family(self, family_id: str, user_id: str, at: datetime) -> None:
|
|
84
|
+
async with self._sessions.begin() as session:
|
|
85
|
+
await session.execute(
|
|
86
|
+
self._families.insert().values(
|
|
87
|
+
id=family_id, user_id=user_id, created_at=at
|
|
88
|
+
)
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
async def add_token(
|
|
92
|
+
self, token_hash: str, family_id: str, issued_at: datetime, expires_at: datetime
|
|
93
|
+
) -> None:
|
|
94
|
+
async with self._sessions.begin() as session:
|
|
95
|
+
await session.execute(
|
|
96
|
+
self._tokens.insert().values(
|
|
97
|
+
token_hash=token_hash,
|
|
98
|
+
family_id=family_id,
|
|
99
|
+
issued_at=issued_at,
|
|
100
|
+
expires_at=expires_at,
|
|
101
|
+
)
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
async def get(self, token_hash: str) -> RefreshRecord | None:
|
|
105
|
+
t, f = self._tokens, self._families
|
|
106
|
+
async with self._sessions() as session:
|
|
107
|
+
row = (
|
|
108
|
+
await session.execute(
|
|
109
|
+
select(
|
|
110
|
+
t.c.token_hash,
|
|
111
|
+
t.c.family_id,
|
|
112
|
+
f.c.user_id,
|
|
113
|
+
t.c.issued_at,
|
|
114
|
+
t.c.expires_at,
|
|
115
|
+
t.c.used_at,
|
|
116
|
+
f.c.revoked_at,
|
|
117
|
+
)
|
|
118
|
+
.join(f, f.c.id == t.c.family_id)
|
|
119
|
+
.where(t.c.token_hash == token_hash)
|
|
120
|
+
)
|
|
121
|
+
).first()
|
|
122
|
+
if row is None:
|
|
123
|
+
return None
|
|
124
|
+
return RefreshRecord(
|
|
125
|
+
token_hash=row.token_hash,
|
|
126
|
+
family_id=row.family_id,
|
|
127
|
+
user_id=row.user_id,
|
|
128
|
+
issued_at=_aware(row.issued_at),
|
|
129
|
+
expires_at=_aware(row.expires_at),
|
|
130
|
+
used_at=_aware(row.used_at),
|
|
131
|
+
family_revoked_at=_aware(row.revoked_at),
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
async def mark_used(self, token_hash: str, at: datetime) -> bool:
|
|
135
|
+
async with self._sessions.begin() as session:
|
|
136
|
+
result = await session.execute(
|
|
137
|
+
update(self._tokens)
|
|
138
|
+
.where(
|
|
139
|
+
self._tokens.c.token_hash == token_hash,
|
|
140
|
+
self._tokens.c.used_at.is_(None),
|
|
141
|
+
)
|
|
142
|
+
.values(used_at=at)
|
|
143
|
+
)
|
|
144
|
+
return result.rowcount == 1
|
|
145
|
+
|
|
146
|
+
async def revoke_family(self, family_id: str, at: datetime) -> None:
|
|
147
|
+
async with self._sessions.begin() as session:
|
|
148
|
+
await session.execute(
|
|
149
|
+
update(self._families)
|
|
150
|
+
.where(
|
|
151
|
+
self._families.c.id == family_id,
|
|
152
|
+
self._families.c.revoked_at.is_(None),
|
|
153
|
+
)
|
|
154
|
+
.values(revoked_at=at)
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
async def revoke_user(self, user_id: str, at: datetime) -> int:
|
|
158
|
+
async with self._sessions.begin() as session:
|
|
159
|
+
result = await session.execute(
|
|
160
|
+
update(self._families)
|
|
161
|
+
.where(
|
|
162
|
+
self._families.c.user_id == user_id,
|
|
163
|
+
self._families.c.revoked_at.is_(None),
|
|
164
|
+
)
|
|
165
|
+
.values(revoked_at=at)
|
|
166
|
+
)
|
|
167
|
+
return result.rowcount
|
|
168
|
+
|
|
169
|
+
async def purge(self, before: datetime) -> int:
|
|
170
|
+
async with self._sessions.begin() as session:
|
|
171
|
+
result = await session.execute(
|
|
172
|
+
delete(self._tokens).where(self._tokens.c.expires_at < before)
|
|
173
|
+
)
|
|
174
|
+
return result.rowcount
|
jwt_sessions/tokens.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Access tokens: short-lived, stateless HS256 JWTs.
|
|
2
|
+
|
|
3
|
+
Stateless on purpose - checking one costs an HMAC, not a database read -
|
|
4
|
+
which is why they are short-lived (15 minutes by default): revoking a
|
|
5
|
+
session takes effect at the next refresh, and an access token outlives its
|
|
6
|
+
session by at most its own lifetime. Refresh tokens are the stateful half
|
|
7
|
+
(`refresh.py`).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from datetime import UTC, datetime, timedelta
|
|
15
|
+
from typing import Any
|
|
16
|
+
from uuid import uuid4
|
|
17
|
+
|
|
18
|
+
import jwt
|
|
19
|
+
|
|
20
|
+
ALGORITHM = "HS256"
|
|
21
|
+
#: Set by the library; an app's extra claims may not replace them.
|
|
22
|
+
RESERVED_CLAIMS = frozenset({"sub", "typ", "iat", "exp", "nbf", "jti", "iss", "aud"})
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class InvalidToken(Exception):
|
|
26
|
+
"""Malformed, forged, expired, or not an access token."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class AccessTokens:
|
|
31
|
+
secret: str
|
|
32
|
+
ttl_seconds: int = 15 * 60
|
|
33
|
+
issuer: str | None = None
|
|
34
|
+
audience: str | None = None
|
|
35
|
+
#: Clock skew tolerated when checking `exp` / `iat`, in seconds.
|
|
36
|
+
leeway_seconds: int = 0
|
|
37
|
+
|
|
38
|
+
def __post_init__(self) -> None:
|
|
39
|
+
# RFC 7518 3.2: an HS256 key must be at least as long as the hash.
|
|
40
|
+
if len(self.secret.encode()) < 32:
|
|
41
|
+
raise ValueError("the signing secret must be at least 32 bytes")
|
|
42
|
+
if self.ttl_seconds <= 0:
|
|
43
|
+
raise ValueError("ttl_seconds must be positive")
|
|
44
|
+
|
|
45
|
+
def issue(
|
|
46
|
+
self,
|
|
47
|
+
subject: str,
|
|
48
|
+
claims: Mapping[str, Any] | None = None,
|
|
49
|
+
*,
|
|
50
|
+
now: datetime | None = None,
|
|
51
|
+
) -> str:
|
|
52
|
+
extra = dict(claims or {})
|
|
53
|
+
clash = RESERVED_CLAIMS.intersection(extra)
|
|
54
|
+
if clash:
|
|
55
|
+
raise ValueError(f"claims may not set {sorted(clash)}")
|
|
56
|
+
now = now or datetime.now(UTC)
|
|
57
|
+
payload: dict[str, Any] = {
|
|
58
|
+
**extra,
|
|
59
|
+
"sub": subject,
|
|
60
|
+
"typ": "access",
|
|
61
|
+
"iat": now,
|
|
62
|
+
"exp": now + timedelta(seconds=self.ttl_seconds),
|
|
63
|
+
"jti": uuid4().hex,
|
|
64
|
+
}
|
|
65
|
+
if self.issuer:
|
|
66
|
+
payload["iss"] = self.issuer
|
|
67
|
+
if self.audience:
|
|
68
|
+
payload["aud"] = self.audience
|
|
69
|
+
return jwt.encode(payload, self.secret, algorithm=ALGORITHM)
|
|
70
|
+
|
|
71
|
+
def verify(self, token: str) -> dict[str, Any]:
|
|
72
|
+
"""The token's claims, or InvalidToken."""
|
|
73
|
+
try:
|
|
74
|
+
claims = jwt.decode(
|
|
75
|
+
token,
|
|
76
|
+
self.secret,
|
|
77
|
+
# Pinned: the algorithm is never taken from the token.
|
|
78
|
+
algorithms=[ALGORITHM],
|
|
79
|
+
issuer=self.issuer,
|
|
80
|
+
audience=self.audience,
|
|
81
|
+
leeway=self.leeway_seconds,
|
|
82
|
+
options={"require": ["sub", "typ", "iat", "exp"]},
|
|
83
|
+
)
|
|
84
|
+
except jwt.PyJWTError as exc:
|
|
85
|
+
raise InvalidToken(str(exc)) from exc
|
|
86
|
+
if claims.get("typ") != "access":
|
|
87
|
+
raise InvalidToken("not an access token")
|
|
88
|
+
return claims
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: jwt-sessions
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: First-party JWT auth for FastAPI with rotating, reuse-detecting refresh tokens.
|
|
5
|
+
Project-URL: Repository, https://github.com/Aegyptiacus11/jwt-sessions
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: auth,fastapi,jwt,refresh-token,session
|
|
9
|
+
Classifier: Framework :: FastAPI
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Session
|
|
12
|
+
Classifier: Topic :: Security
|
|
13
|
+
Requires-Python: >=3.11
|
|
14
|
+
Requires-Dist: pwdlib[argon2]>=0.2
|
|
15
|
+
Requires-Dist: pyjwt>=2.8
|
|
16
|
+
Provides-Extra: fastapi
|
|
17
|
+
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
|
|
18
|
+
Provides-Extra: sqlalchemy
|
|
19
|
+
Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'sqlalchemy'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# jwt-sessions
|
|
23
|
+
|
|
24
|
+
First-party authentication for FastAPI: email and password sign-in,
|
|
25
|
+
short-lived access tokens, and refresh tokens that rotate on every use and
|
|
26
|
+
give themselves away when stolen.
|
|
27
|
+
|
|
28
|
+
It is for applications that own their users and do not want an identity
|
|
29
|
+
provider. Authorization - who may do what - is deliberately not here; it
|
|
30
|
+
belongs to the application.
|
|
31
|
+
|
|
32
|
+
> Status: 0.1.0, the first release, extracted from a production application; the
|
|
33
|
+
> API may still change before 1.0. MIT licensed.
|
|
34
|
+
|
|
35
|
+
## Installing
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
uv add "jwt-sessions[fastapi,sqlalchemy]"
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
(or `pip install`, with the same argument). The extras are the FastAPI router and the
|
|
42
|
+
SQLAlchemy refresh store.
|
|
43
|
+
|
|
44
|
+
## Using it
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from jwt_sessions import AccessTokens, Auth, RefreshTokens
|
|
48
|
+
from jwt_sessions.fastapi import auth_router, bearer_claims
|
|
49
|
+
from jwt_sessions.sqlalchemy_store import SQLAlchemyRefreshStore, refresh_tables
|
|
50
|
+
|
|
51
|
+
families, tokens = refresh_tables(Base.metadata) # on your own metadata
|
|
52
|
+
auth = Auth(
|
|
53
|
+
users=MyUsers(), # by_login / by_id -> AuthUser
|
|
54
|
+
access=AccessTokens(settings.jwt_secret),
|
|
55
|
+
refresh=RefreshTokens(SQLAlchemyRefreshStore(sessionmaker, families, tokens)),
|
|
56
|
+
)
|
|
57
|
+
app.include_router(auth_router(auth), prefix="/api/v1")
|
|
58
|
+
current_claims = bearer_claims(auth) # a dependency: the verified claims
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`examples/demo_app.py` is a complete, runnable one:
|
|
62
|
+
`uv run uvicorn examples.demo_app:app`.
|
|
63
|
+
|
|
64
|
+
## The contract
|
|
65
|
+
|
|
66
|
+
| | Request | Response |
|
|
67
|
+
|---|---|---|
|
|
68
|
+
| `POST /auth/login` | `{"email", "password"}` | `{"access_token", "token_type"}` + the refresh cookie |
|
|
69
|
+
| `POST /auth/refresh` | the refresh cookie | a new access token + the rotated cookie |
|
|
70
|
+
| `POST /auth/logout` | the refresh cookie | `204`; that session is revoked, the cookie cleared |
|
|
71
|
+
| `POST /auth/logout-all` | `Authorization: Bearer` | `204`; every session of the user is revoked |
|
|
72
|
+
|
|
73
|
+
- **The access token** is a JWT (HS256, 15 minutes by default), sent as
|
|
74
|
+
`Authorization: Bearer`. It is never in a cookie, so no request is authorised
|
|
75
|
+
by a cookie alone.
|
|
76
|
+
- **The refresh token** is an opaque random value that only ever travels in an
|
|
77
|
+
`httpOnly`, `SameSite=Lax` cookie scoped to the auth endpoints. JavaScript
|
|
78
|
+
never sees it, so a script injected into the page cannot take it away.
|
|
79
|
+
|
|
80
|
+
### What a client has to do
|
|
81
|
+
|
|
82
|
+
A browser client is small - there is no client library, and the contract is
|
|
83
|
+
all it needs:
|
|
84
|
+
|
|
85
|
+
- Keep the access token in memory, not in storage.
|
|
86
|
+
- Call the auth endpoints with `credentials: "include"`, so the cookie travels.
|
|
87
|
+
- On load, `POST /auth/refresh` to restore a session; a 401 means signed out.
|
|
88
|
+
- On a 401 from the API, refresh **once** and retry; if the refresh fails, the
|
|
89
|
+
session is gone.
|
|
90
|
+
- Never run two refreshes at once from one page: the server spends a refresh
|
|
91
|
+
token on use, and the second would look like a replay (see below). Share one
|
|
92
|
+
in-flight refresh between everything that needs a token.
|
|
93
|
+
- Renewing a minute before the access token's `exp` saves the first request
|
|
94
|
+
after an idle spell a round trip.
|
|
95
|
+
|
|
96
|
+
## What happens to a stolen refresh token
|
|
97
|
+
|
|
98
|
+
A sign-in starts a **family** of refresh tokens. Each refresh spends the
|
|
99
|
+
token presented and issues its successor. A spent token presented again means
|
|
100
|
+
two parties hold it - the user and whoever copied it - so the whole family is
|
|
101
|
+
revoked: both are signed out, and the copy is dead.
|
|
102
|
+
|
|
103
|
+
A stateless refresh JWT, the usual alternative, can do none of this: a copied
|
|
104
|
+
one keeps working until it expires, however often its owner refreshes, and
|
|
105
|
+
signing out only deletes the owner's copy.
|
|
106
|
+
|
|
107
|
+
Two tabs refreshing at the same instant would look like a replay, so a spent
|
|
108
|
+
token presented again within `reuse_grace_seconds` (10 s by default; 0 turns it
|
|
109
|
+
off) gets a successor instead. That window is open to a thief as well, if they
|
|
110
|
+
replay within those seconds of the real refresh.
|
|
111
|
+
|
|
112
|
+
Only the SHA-256 of a refresh token is stored, so a copy of the table holds
|
|
113
|
+
nothing that can be presented.
|
|
114
|
+
|
|
115
|
+
## Also
|
|
116
|
+
|
|
117
|
+
- Signing in with an unknown email costs the same argon2 verification as a
|
|
118
|
+
wrong password, so response time does not say which addresses have accounts.
|
|
119
|
+
- Passwords over 1 KB are refused before hashing.
|
|
120
|
+
- The signing secret must be at least 32 bytes, and the JWT algorithm is pinned
|
|
121
|
+
on verification, never read from the token.
|
|
122
|
+
- A deactivated account's session ends at its next refresh; its current access
|
|
123
|
+
token runs out within the access TTL. `Auth.logout_everywhere` ends every
|
|
124
|
+
session at once - call it on deactivation and on a password change.
|
|
125
|
+
- `RefreshStore.purge` drops expired tokens; run it now and then (on start-up
|
|
126
|
+
is enough for most applications).
|
|
127
|
+
|
|
128
|
+
## Development
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
uv run pytest
|
|
132
|
+
uv run ruff check . && uv run ruff format --check .
|
|
133
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
jwt_sessions/__init__.py,sha256=dLtOfdGVrNDkJ5cvtbhx36ZisbZEKimaWcuH0s7Xq9I,725
|
|
2
|
+
jwt_sessions/core.py,sha256=-eNsdpURe3MVgrFEAS6u8QCZBfV_-iOEVfjMhxDEERI,3305
|
|
3
|
+
jwt_sessions/fastapi.py,sha256=vJq4wvcq2rdvK7DB3QybzS_RlxwiYrEfCpT_Y9bteBE,6987
|
|
4
|
+
jwt_sessions/memory.py,sha256=SW_3UJ_Ak1XGUgBVKLHmXyHGYXhV5NYBrDeAvOkPno0,2520
|
|
5
|
+
jwt_sessions/passwords.py,sha256=GOA-w3y49GIvSNqL4zvf8qzXm7ekDJUba7GW2P-c898,1434
|
|
6
|
+
jwt_sessions/refresh.py,sha256=YCvVurMjC3hLdCovSF3Nl80yY3exCxlBFyZijkMSEio,5800
|
|
7
|
+
jwt_sessions/sqlalchemy_store.py,sha256=XvsUfzpqWdOUBMYoIYFtqYoyArHZuCe3hMCnvvvPJ3w,6067
|
|
8
|
+
jwt_sessions/tokens.py,sha256=PtYHcKsVIXX8erWXfW0vNZEMZVyaTLx28QRh_Wq30Tk,2966
|
|
9
|
+
jwt_sessions-0.1.0.dist-info/METADATA,sha256=2PyMpFYNVe20EQmdfMMCLdkdYJGxbEDwYq8YkByS2yQ,5464
|
|
10
|
+
jwt_sessions-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
11
|
+
jwt_sessions-0.1.0.dist-info/licenses/LICENSE,sha256=zeZOi0a-ED0vroPKLvyIcyGUhY5Ngn7i7JSBiveQt2c,1072
|
|
12
|
+
jwt_sessions-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nassim Kaddouri
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|