question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using Access Token (OAuth2) generated in subsequent requests

See original GitHub issue

Hi, 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:closed
  • Created 2 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
tiangolocommented, Dec 9, 2022

Thanks for the help here @dnutiu ! 👏 🙇

Thanks for coming back and closing the issue @eliasyishak 👍

Sorry for the long delay! 🙈 I wanted to personally address each issue/PR and they piled up through time, but now I’m checking each one in order.

0reactions
dnutiucommented, May 5, 2021

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:

That makes more sense, do you know how to retrieve data stored in localStorage within FastAPI functions?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/tiangolo/fastapi/issues/3175#issuecomment-832778872, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABUGDAS4YBAUQDLHXK5CKHDTMFPF5ANCNFSM44DSZCMQ .

Read more comments on GitHub >

github_iconTop Results From Across the Web

Making Authenticated Requests - OAuth 2.0 Simplified
The only thing your application should do with it is use it to make API requests. Some services will use structured tokens like...
Read more >
OAuth 2 Access Token Usage Strategies for Multiple ...
If using the Client Credentials Grant, it should be easy enough to request additional tokens by replaying the original token request.
Read more >
Using OAuth 2.0 to Access Google APIs | Authorization
1. Obtain OAuth 2.0 credentials from the Google API Console. 2. Obtain an access token from the Google Authorization Server. 3.
Read more >
Should an oAuth server give the same accessToken to a same ...
Once your access token expires, you should inform user about that and user should re-request for new access token providing one-time-use refresh ...
Read more >
Obtaining Token Using OAuth Grant Mechanism
Step 1: Authenticate a User and Create a User Session · Step 2: [Optional] Generating Client Credentials · Step 3: Generate Authorization Code...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found