Token undefined? #7586
-
First check
DescriptionWhen I try to run read_user_me on I definitely can’t understand if this is a bug, or an error in my code. Maybe I should use cookies... python 3.8 ....
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="/token",
scopes={"me": "Read information about the current user."},
)
async def get_current_user(
security_scopes: SecurityScopes,
token: str = Depends(oauth2_scheme)
):
pb_key = usecases.users.GetPublicKey().execute()
if security_scopes.scopes:
authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
else:
authenticate_value = f"Bearer"
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Doesn't work :'(",
headers={"WWW-Authenticate": authenticate_value},
)
try:
payload = jwt.decode(token, pb_key, algorithms=['RS256'])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_scopes = payload.get("scopes", [])
token_data = entities.TokenData(scopes=token_scopes, username=username)
except (PyJWTError, ValidationError):
raise credentials_exception
user = usecases.users.ReadByUsername().execute(user_name=username)
for scope in security_scopes.scopes:
if scope not in token_data.scopes:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not enough permissions",
headers={"WWW-Authenticate": authenticate_value},
)
return user
app = FastAPI(default_response_class=JSONAPIResponse)
@app.post(
"/token",
response_model=entities.Token,
tags=["auth"]
)
async def login_for_access_token(
from_data: OAuth2PasswordRequestForm = Depends()
):
token = users_usecases.AuthUser().execute(
user_name=from_data.username,
password=from_data.password
)
return token.value.dict()
@app.get(
"/me",
response_model=users_presenter.UserJSONObject
)
async def read_user_me(
current_user: users_presenter.UserJSONObject = Security(
get_current_user,
scopes=["me"]
)
):
return JSONAPIConverter().serialize(current_user)
....Additional contextI have JSON-API entities and classes of user cases for manipulating data from the database |
Beta Was this translation helpful? Give feedback.
Replies: 10 comments
-
|
This undefined does not look like Python generated. Did you test this with a browser (since you did not mention how you test this)? |
Beta Was this translation helpful? Give feedback.
-
|
I test this with a browser, of course. I changed my code and now I have: async def login_for_access_token(
from_data: OAuth2PasswordRequestForm = Depends()
):
token = users_usecases.AuthUser().execute(
user_name=from_data.username,
password=from_data.password
)
return {"access_token": token.value, "token_type": "bearer"}This code looks like the code from the offical tutorial. Perhaps the problem is parsing entities. At the output, I got JSON: API entity, and now just what was in the tutorial and it worked. |
Beta Was this translation helpful? Give feedback.
-
|
I think I should create new bug issue. I took the code from the official tutorial and replaced the output values for the endpoint: @app.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username, "scopes": form_data.scopes},
expires_delta=access_token_expires,
)
return {
"data": {
"id": "1",
"types": "tokens",
"attributes": {
"value": access_token
}
}
} Perhaps there is no mistake and I just do not fully understand how the dependencies work. |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for the help here @phy25 ! 🙇 @idmitryz please provide a simple, self-contained example that shows your error, otherwise, it's very difficult to guess what might be wrong. |
Beta Was this translation helpful? Give feedback.
-
|
Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues. |
Beta Was this translation helpful? Give feedback.
-
|
Actually, I'm noticing the same issue. Can anybody post how they solved it? |
Beta Was this translation helpful? Give feedback.
-
|
If it helps, I just ran into this and it was because the Swagger-UI was not adding the token to the Authorization header. It was doing this because I had the class Token(BaseModel):
access_token: str
token_type: str
class Config:
alias_generator = camel.case |
Beta Was this translation helpful? Give feedback.
-
{
"access_token": "token",
"token_type": "bearer"
}above works well. the following results in : {
"errcode": 10000,
"errmsg": "",
"data": {
"access_token": "token",
"token_type": "bearer"
}
} |
Beta Was this translation helpful? Give feedback.
-
|
@einsone did you find a way to solve this problem? |
Beta Was this translation helpful? Give feedback.
-
|
Token endpoint should return token with "access_token" key. |
Beta Was this translation helpful? Give feedback.
Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.