Using Access Token (OAuth2) generated in subsequent requests
See original GitHub issueHi, I am just getting started with FastAPI and have been a little stuck working with the authentication piece of my project using the OAuth2 flow.
from datetime import datetime, timedelta
from typing import Optional
import uvicorn
from fastapi import Depends, FastAPI, HTTPException, status, Request
from fastapi.responses import RedirectResponse
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
# Import the necessary libraries
from fastapi.templating import Jinja2Templates
# Mount the templates with Jinja
templates = Jinja2Templates(directory="templates")
# to get a string like this run:
# openssl rand -hex 32
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
fake_users_db = {
"johndoe": {
"username": "johndoe",
"full_name": "John Doe",
"email": "johndoe@example.com",
"hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
"disabled": False,
}
}
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
app = FastAPI()
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
@app.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
print(form_data.__dict__)
if form_data.username not in fake_users_db:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": form_data.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/")
async def index(request: Request, token: str = Depends(oauth2_scheme)):
return token
@app.get("/login")
async def login(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
if __name__ == "__main__":
uvicorn.run("test:app", reload=True)
<form action="/token" method="post">
<div class="container">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<button type="submit">Login</button>
</div>
</form>
The first block is the python code that executes the application and the second block is the html code the user will interact with from a browser.
When a user navigates to “/login”, they will fill out the form and when they hit submit, it will hit the post route for “/token”. (The correct username is “john” and password is “doe”). When the user hits submit, they will get the newly generated access token.
However, I would like to now be able to use that newly generated access token in subsequent requests. I attempted to use RedirectResponse with custom headers, but the custom headers get dropped when I try to reroute to “/”.
I feel like I am missing something obvious so any help would be greatly appreciated!
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (1 by maintainers)
Top GitHub Comments
Thanks for the help here @dnutiu ! 👏 🙇
Thanks for coming back and closing the issue @eliasyishak 👍
Hi,
The localStorage API is a browser API, it’s available in Chrome, Firefox, Edge and most recent browsers.
On Wed, May 5, 2021, 18:23 eliasyishak @.***> wrote: