authx icon indicating copy to clipboard operation
authx copied to clipboard

refresh_token_required is unuseful

Open JackyNiu opened this issue 1 year ago • 10 comments

this is my code copyed in document authx document method: refresh_token_required raise 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)

JackyNiu avatar Apr 09 '24 17:04 JackyNiu

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.

yokoberek avatar Jun 14 '24 09:06 yokoberek

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. 🙏🏻

yezz123 avatar Jun 14 '24 10:06 yezz123

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

HAWK-Soft avatar Jun 17 '24 13:06 HAWK-Soft

Same for me. Someone found a solution for this?

What I did while the issue is being fixed is instead of creating a refresh_token directly when a user logs in, I create another access_token with an expiration time of 60 days and use it as a refresh_token. I know it's not the right way to do it, but it works.

Batres35 avatar Aug 22 '24 04:08 Batres35