Skip to content

33. Get Current User


1. Get Current User

  • 이전 예제에서 다음과 같이 path operation function에 str 타입의 token을 제공했다.


from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/items/")
async def read_items(token: str = Depends(oauth2_scheme)):
    return {"token": token}


  • 하지만 이것만으로는 유용한 코드라고 볼 수 없다.


2. Create a user model

  • 다음과 같이 Pydantic user 모델을 생성한다.


from typing import Optional
from pydantic import BaseModel
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None

def fake_decode_token(token):
    return User(
        username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
    )

async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = fake_decode_token(token)

    return user

@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user


3. Create a get_current_user dependency

  • dependency get_current_user를 생성해 보자.
  • dependencies는 sub-dependencies를 가질 수 있는데, get_current_user는 이전에 생성한 것과 동일한 dependency oauth2_scheme를 갖는다.


  • 이전에 path operation에서 직접 수행했던 것과 동일하게 새로운 dependency get_current_user는 다음과 같이 sub-dependency oauth2_scheme에서 str 타입의 token을 받는다.


from typing import Optional
from pydantic import BaseModel
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None

def fake_decode_token(token):
    return User(
        username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
    )

async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = fake_decode_token(token)

    return user

@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user


4. Get the user

  • 다음과 같이 get_current_userstr 타입의 token을 받아서 Pydantic User 모델을 반환하는 fake_decode_token을 사용한다.


from typing import Optional
from pydantic import BaseModel
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None

def fake_decode_token(token):
    return User(
        username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
    )

async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = fake_decode_token(token)

    return user

@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user


5. Inject the current user

  • 다음과 같이 path operation에서 get_current_user와 동일한 Depends를 사용할 수 있다.


from typing import Optional
from pydantic import BaseModel
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None

def fake_decode_token(token):
    return User(
        username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
    )

async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = fake_decode_token(token)

    return user

@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user


  • 위의 예제에서 current_user의 타입으로 Pydantic User 모델을 선언했다.
  • 이렇게 하면 자동 완성 등의 기능을 지원받을 수 있다.

References