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.

[QUESTION] /docs - how to add the token to authorize button?

See original GitHub issue

How to add the token to authorize button?

First of all I want to congratulate you for the excellent work on FastApi and give my apologize for my english.

I did not find the way to add a Bearer Token to the Authorize Button on “docs page”.

Could you help me? Attach an example

Thanks in advance !!!

Adrián

from fastapi import FastAPI, HTTPException, Security, Depends
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware
import jwt
from datetime import datetime, timedelta

SECRET_KEY = "25cda665298a1ac9a0b5bcf37ddf1c5523f42ccb5cc1f347218b46d42cce7053"
ALGORITHM = "HS256"

class UsuarioGetToken(BaseModel):
    email: str
    password: str = None

class Usuario_Session(BaseModel):
    usuario_id: int
    nombre: str 

class Token(BaseModel):
    token_type: str
    token: str

# FastAPI specific code
app = FastAPI(title='API Test', version='0.1')
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
token_check = OAuth2PasswordBearer(tokenUrl="/login")    


def get_current_user(token: str = Security(token_check)):
    try:    
        usuario_session = jwt.decode(token, SECRET_KEY, algorithm=ALGORITHM)
    except:
        raise HTTPException(status_code=401, detail="Sessión inválida")    
    return Usuario_Session(**usuario_session)  
    
# Dependency
@app.post("/login", response_model=Token, summary="Autentificación de usuario")
def login(user: UsuarioGetToken):
    to_encode = {"usuario_id": 1, "nombre": user.email}
    expire = datetime.utcnow() + timedelta(minutes=60)
    to_encode.update({"exp": expire, "sub": "Test"})
    access_token = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return Token(token = access_token, token_type = 'Bearer')

@app.get("/test")
def test(current_user: Usuario_Session = Depends(get_current_user)):
    # Verifico los datos
    return {'data': 'ok'}

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
tiangolocommented, Apr 27, 2019

@adriangallegos you have a couple of bugs in the example:

  • The JSON containing the token returned MUST have a key access_token, token alone won’t work.
  • By declaring user: UsuarioGetToken in login() you are declaring a JSON body. The OAuth 2.0 spec requires you to receive form data, not JSON, and the fields have to be username (not email) and password.
    • For this, use the provided OAuth2PasswordRequestForm, import it and use it as a dependency.
    • Read OAuth2PasswordRequestForm.username to get the email of your user. You can use emails as usernames, as long as for authentication you use exactly username. That’s not a limitation of FastAPI, is part of the spec.

Here’s your same code with the minimal changes to work:

from fastapi import FastAPI, HTTPException, Security, Depends
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware
import jwt
from datetime import datetime, timedelta

SECRET_KEY = "25cda665298a1ac9a0b5bcf37ddf1c5523f42ccb5cc1f347218b46d42cce7053"
ALGORITHM = "HS256"

class Usuario_Session(BaseModel):
    usuario_id: int
    nombre: str 

class Token(BaseModel):
    token_type: str
    access_token: str

# FastAPI specific code
app = FastAPI(title='API Test', version='0.1')
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
token_check = OAuth2PasswordBearer(tokenUrl="/login")    


def get_current_user(token: str = Security(token_check)):
    try:    
        usuario_session = jwt.decode(token, SECRET_KEY, algorithm=ALGORITHM)
    except:
        raise HTTPException(status_code=401, detail="Sessión inválida")    
    return Usuario_Session(**usuario_session)  
    
# Dependency
@app.post("/login", response_model=Token, summary="Autentificación de usuario")
def login(form_data: OAuth2PasswordRequestForm = Depends()):
    to_encode = {"usuario_id": 1, "nombre": form_data.username}
    expire = datetime.utcnow() + timedelta(minutes=60)
    to_encode.update({"exp": expire, "sub": "Test"})
    access_token = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return Token(access_token = access_token, token_type = 'Bearer')

@app.get("/test")
def test(current_user: Usuario_Session = Depends(get_current_user)):
    # Verifico los datos
    return {'data': 'ok'}
0reactions
ahsanrossicommented, May 23, 2022

Hi there , i am facing this method not allowed error while doing authenticattion

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using the token model | Authorization - Google Developers
Use the requestAccessToken() method to trigger the token UX flow and obtain an access token. Google prompts the user to: Choose their account, ......
Read more >
Enable Authorize button in springdoc-openapi-ui for Bearer ...
I prefer to use bean initialization instead of annotation. import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.
Read more >
Authorizing requests | Cloud DNS - Google Cloud
Every request your application sends to the Cloud DNS API must include an authorization token. The token also identifies your application to Google....
Read more >
Security - First Steps - FastAPI
You already have a shiny new "Authorize" button. ... The API checks that username and password , and responds with a "token" (we...
Read more >
Retrieve an Access Token and Refresh Token
As soon as the Device Authorization Request returns a response, you should begin making Device Token Requests to the token endpoint ...
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