[QUESTION] /docs - how to add the token to authorize button?
See original GitHub issueHow 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:
- Created 4 years ago
- Comments:8 (4 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@adriangallegos you have a couple of bugs in the example:
access_token
,token
alone won’t work.user: UsuarioGetToken
inlogin()
you are declaring a JSON body. The OAuth 2.0 spec requires you to receive form data, not JSON, and the fields have to beusername
(notemail
) andpassword
.OAuth2PasswordRequestForm
, import it and use it as a dependency.OAuth2PasswordRequestForm.username
to get the email of your user. You can use emails as usernames, as long as for authentication you use exactlyusername
. That’s not a limitation of FastAPI, is part of the spec.Here’s your same code with the minimal changes to work:
Hi there , i am facing this method not allowed error while doing authenticattion