-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt_auth_example.py
More file actions
44 lines (36 loc) · 1.18 KB
/
jwt_auth_example.py
File metadata and controls
44 lines (36 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File: /jwt_auth_example.py
from apispark.app import ApiSparkApp
from pydantic import BaseModel
from fastapi import Depends
from datetime import timedelta
# Configuration
SECRET_KEY = "your_secret_key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
app_instance = ApiSparkApp(
security="jwt",
secret=SECRET_KEY,
algorithm=ALGORITHM,
access_token_expire_minutes=ACCESS_TOKEN_EXPIRE_MINUTES
)
app = app_instance.get_app()
class Item(BaseModel):
name: str
price: float
class Token(BaseModel):
access_token: str
token_type: str
@app.get("/items")
def get_items():
return {"message": "Fetching all items"}
@app.post("/item")
def post_item(item: Item, token: str = Depends(app_instance.auth.jwt_required)):
return {"message": f"Item {item.name} added"}
@app.post("/token", response_model=Token)
async def login_for_access_token():
# Assuming authentication is successful
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = app_instance.auth.jwt_auth.create_access_token(
data={"sub": "user_id"}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}