Nextjs and flask app using auth0 - getting token errors

hey - I have a Next.js app that uses auth0 for login. The app uses a flask back end to query a database. I need the back end to know who the user is so I’m sending a token with each request in auth headers.

I’m new to front end dev and even newer to back end. So this is quite a challenge for me.

With my requests I now get an error saying “Error decoding token headers.” in my api reponses.

Here is my relevant back end code:

def get_rsa_key(token):
# Get the JWKS from Auth0
response = requests.get(f’https://{AUTH0_DOMAIN}/.well-known/jwks.json’)
jwks = response.json()

# Get the unverified header from the token
unverified_header = jwt.get_unverified_header(token)

# Print unverified header and JWKS
logging.info(f'Unverified Header: {unverified_header}')
logging.info(f'JWKS: {jwks}')

# Find the key which matches the `kid` in the JWT header
rsa_key = {}
for key in jwks['keys']:
    if key['kid'] == unverified_header['kid']:
        rsa_key = jwk.construct(key)
        break

return rsa_key

def get_user_info(token):
# Send a request to the /userinfo endpoint with the token
response = requests.get(
f’https://{AUTH0_DOMAIN}/userinfo’,
headers={‘Authorization’: f’Bearer {token}'}
)

# The response should be a JSON object containing user info
user_info = response.json()
return user_info

@app.before_request
def before_request():
logging.info(‘before_request function called’)

#handle options
if request.method == 'OPTIONS':
    return None

# Skip validation for endpoints that don't need it
if request.path in []:
    return

# # unprotected routes could be declared like this
# if request.path in ['/api/columns', '/matrixcolumns', '/query', '/benchmark']:
#     return

auth_header = request.headers.get('Authorization', None)
logging.info(f'Authorization Header: {auth_header}')
if not auth_header:
    logging.info('No auth header')
    return jsonify({'error': 'No Authorization header'}), 401

parts = auth_header.split()

if parts[0].lower() != 'bearer':
    return jsonify({'error': 'Invalid Authorization header format. Expected "Bearer <token>"'}), 401
elif len(parts) == 1:
    return jsonify({'error': 'Invalid Authorization header, no token'}), 401
elif len(parts) > 2:
    return jsonify({'error': 'Invalid Authorization header, should contain only "Bearer <token>"'}), 401

token = parts[1]
logging.info(f'Parsed Token: {token}')
try:
    rsa_key = get_rsa_key(token)
    logging.info(f'RSA Key: {rsa_key}')
    if not rsa_key:
        return jsonify({'error': 'Unable to find appropriate key'}), 401

    payload = jwt.decode(
        token,
        rsa_key.to_dict(),
        algorithms=['RS256'],
        audience=API_AUDIENCE,
        issuer=f'https://{AUTH0_DOMAIN}/'
    )
    logging.info(f'Decoded Payload: {payload}')
except JWTError as error:
    return jsonify({'error': str(error)}), 401

# Get user info
user_info = get_user_info(token)

# Print user info
logging.info(f"User Info: {user_info}")

Am I doing something wrong? Please use small words :slight_smile: :rofl:

further to this, I think the token I’m using is encrypted rather than signed. I think it should be signed instead??

But can’t find the settings in auth0 to check or change. I think the settings are good as they are but would appreciate a little help. Thanks