question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Token undefined?

See original GitHub issue

First check

  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.

Description

When I try to run read_user_me on "/me" endpoint, an undefined (empty?) Token enters the function get_current_user (I saw it in debuger 'token='undefined') and after this I get "Authorization: Bearer undefined"

I definitely can’t understand if this is a bug, or an error in my code. Maybe I should use cookies…

python 3.8 last versions of libs

....
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 context

I have JSON-API entities and classes of user cases for manipulating data from the database

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
coryvirokcommented, Aug 12, 2020

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 Token() model from the example in the docs but I was also using an alias generator that was camelCasing the response.

class Token(BaseModel):
    access_token: str
    token_type: str

    class Config:
        alias_generator = camel.case

https://stackoverflow.com/questions/59808854/swagger-authorization-bearer-not-send#:~:text=In the cURL request you,header%2C it cannot be found.

0reactions
einsonecommented, Mar 26, 2021
{
    "access_token": "token",
    "token_type": "bearer"
}

above works well.

the following results in : -H 'Authorization: Bearer undefined'

{
    "errcode": 10000,
    "errmsg": "",
    "data": {
        "access_token": "token",
        "token_type": "bearer"
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Attempt to get token returns undefined - Stack Overflow
Attempt to get token returns undefined · 2. response.text() gives you a string. Strings do not have a .token attribute. – VLAZ. May...
Read more >
Relevance Question -- Token value undefined
I've come across a scenario where we create a question condition based on a custom participant attribute... And when we set the rule,...
Read more >
How to reliably obtain a control sequence token which is ...
I ask for the best way of obtaining a control sequence token that is undefined in the current scope.
Read more >
[Github] Token is not valid: undefined - Questions - n8n
I'm getting the following error when trying to integrate with Github I have noticed that the personal access tokens now seem to be...
Read more >
Undefined refresh token - OAuth/OIDC
Hello, I can't get a refresh token. It returns undefined. Thank you! import NextAuth from 'next-auth' import OktaProvider from ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found