Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

377
Visualizações
How to implement OAuth to FastAPI with client ID & Secret

I have followed the docs about Oauth2 but it does not describe the proccess to add client id and secret

https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/

and what this does

class UserInDB(User):
    hashed_password: str

from the original example

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In documentation it uses OAuth2PasswordRequestForm to authenticate the user this class has basically 6 different Fields,

grant_type: str = Form(None, regex="password"),
username: str = Form(...),
password: str = Form(...),
scope: str = Form(""),
client_id: Optional[str] = Form(None),
client_secret: Optional[str] = Form(None),

So you can add client_id and client_secret,if you are interested Repository here.

But i usally prefer authlib, it saves so much time makes it easier. Here is a complete example of how you can create a OAuth with authlib

First create a OAuth Client

from authlib.integrations.starlette_client import OAuth
from starlette.config import Config

config = Config('.env')  # read config from .env file
oauth = OAuth(config)
oauth.register(
    name='google',
    server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
    client_kwargs={
        'scope': 'openid email profile'
    }
)

We don't need to add client_id and client_secret here, because they are in .env file. You are not supposed to hard code them in the code in real products.Google has an OpenID discovery endpoint, we can use this URL for server_metadata_url. Authlib will automatically fetch this server_metadata_url to configure the OAuth client for you.

Now we will create a FastAPI application to define a login route.

from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="secret-string")

We need this SessionMiddleware, because Authlib will use request.session to store temporary codes and states. The below code which is /login endpoint, will redirect you to Google account website.

@app.route('/login')
async def login(request: Request):
    redirect_uri = request.url_for('auth')
    return await oauth.google.authorize_redirect(request, redirect_uri

When you grant access from Google website, Google will redirect back to your given redirect_uri, which is request.url_for('auth'):

@app.route('/auth')
async def auth(request: Request):
    token = await oauth.google.authorize_access_token(request)
    user = await oauth.google.parse_id_token(request, token)
    return user

The above code will obtain a token which contains access_token and id_token. An id_token contains user info, we just need to parse it to get the login user's information.

Sources: Authlib-FastAPI-Google-Login

Also if you still wanna use Pure FastAPI check this link FastAPI OAuth2PasswordRequestForm

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda