yezz123 / authx

Ready-to-use and customizable Authentications and Oauth2 management for FastAPI ✨
https://authx.yezz.me/
MIT License
754 stars 46 forks source link

refresh_token_required is unuseful #572

Open JackyNiu opened 3 months ago

JackyNiu commented 3 months ago

this is my code copyed in document authx document method: refresh_token_requiredraise Exception authx.exceptions.MissingTokenError: No token found in request from '[]'

from pydantic import BaseModel
from fastapi import FastAPI, Depends, HTTPException
from authx import AuthX, TokenPayload, AuthXConfig

auth_config = AuthXConfig()

auth_config.JWT_ALGORITHM = 'HS256'
auth_config.JWT_SECRET_KEY = 'SECRET_KEY'

auth_config.JWT_TOKEN_LOCATION = ['headers']

app = FastAPI()
security = AuthX(auth_config)

class LoginForm(BaseModel):
    username: str
    password: str

@app.post('/login')
def login(data: LoginForm):
    if data.username == "test" and data.password == "test":
        access_token = security.create_access_token(data.username)
        refresh_token = security.create_refresh_token(data.username)
        return {
            "access_token": access_token,
            "refresh_token": refresh_token
        }
    raise HTTPException(401, "Bad username/password")

@app.post('/refresh')
def refresh(
    refresh_payload: TokenPayload = Depends(security.refresh_token_required)
):
    """
    TODO refresh_token_required error
    """
    access_token = security.create_access_token(refresh_payload.sub)
    return {"access_token": access_token}

@app.get('/protected', dependencies=[Depends(security.access_token_required)])
def protected():
    return "You have access to this protected resource"

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, port=8000)
yokoberek commented 1 month ago

Is there any solution? I am also having the same problem.

Edit: For now, I resolved this by changing JSON_TOKEN_LOCATION from headers to json and sending the refresh token in the body instead of the request header.

yezz123 commented 1 month ago

Hey @JackyNiu @yokoberek,

I will investigate this over the next few days to see how I can solve it. From what I understand, it might be related to passing the token in the request header. 🙏🏻

HAWK-Soft commented 1 month ago

Same for me. Thanks for the tip @yokoberek it works now