requests-oauthlib icon indicating copy to clipboard operation
requests-oauthlib copied to clipboard

refresh token and required client secret

Open tamis-laan opened this issue 1 year ago • 0 comments

I'm trying to implement token refresh using zitadel, fastapi + request-oauthlib using the PCKE flow as followed:

@router.get("/refresh-token")
async def refresh_token(request: Request, response: Response):

    # Log to console
    logger.info("Attempting to refresh access token.")

    # Get the configuration
    config = get_config()

    print("TRACE 00001")

    # Get the session refresh token
    refresh_token = await request.state.session.get('refresh_token')

    print("TRACE 00002")

    # Check err
    if not refresh_token:
        logger.error("No refresh token available in session.")
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Refresh token not found.")

    print("TRACE 00003")

    # Create oauth client
    oauth2 = OAuth2Session(
        client_id=config['client_id'],
        scope=config['scope']
    )

    print("TRACE 00004")

    # Refresh the token
    try:
        new_token = oauth2.refresh_token(
            token_url=config['oid_config']['token_endpoint'],
            refresh_token=refresh_token,
            client_id=config['client_id']
        )
    except Exception as e:
        logger.error(f"Failed to refresh token: {str(e)}")
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e))

    print("TRACE 00005")

    # Store new refresh token
    await request.state.session.put('refresh_token', new_token.get('refresh_token', refresh_token))

    print("TRACE 00006")

    # Store new access token
    await request.state.session.put('access_token', new_token['access_token'])

    print("TRACE 00007")

    original_url = await request.state.session.get('original_url', '/dead')
    response = RedirectResponse(url=original_url)
    response.set_cookie(key="access_token", value=new_token['access_token'], httponly=True)

    return response

But I get the error Failed to refresh token: (invalid_client) empty client secret. However I would expect no client secret is needed when using PCKE.

And If I remove the client id from oauth2.refresh_token as so:

new_token = oauth2.refresh_token(
    token_url=config['oid_config']['token_endpoint'],
    refresh_token=refresh_token
)

I get the following back from the zitadel server:

ERROR:auth:Failed to refresh token: (invalid_request) client_id or client_assertion must be provided

So I'm in a catch 22.

Anything I should be doing different??

tamis-laan avatar Aug 26 '24 19:08 tamis-laan