Securing endpoints with access tokens
Previously, we learned how to implement a simple dependency to protect an endpoint with a header. Here, we’ll also retrieve a token from a request header, but then, we’ll have to check the database to see whether it’s valid. If it is, we’ll return the corresponding user.
Let’s see what our dependency looks like:
app.py
async def get_current_user( token: str = Depends(OAuth2PasswordBearer(tokenUrl="/token")), session: AsyncSession = Depends(get_async_session), ) -> User: query = select(AccessToken).where( AccessToken.access_token == token, AccessToken.expiration_date >= datetime.now(tz=timezone.utc), ) result = await session.execute(query) access_token...