async def test_hubauth_token(app, mockservice_url, create_user_with_scopes):
    """Test HubAuthenticated service with user API tokens"""
    u = create_user_with_scopes("access:services")
    token = u.new_api_token()
    no_access_token = u.new_api_token(roles=[])
    app.db.commit()

    # token without sufficient permission in Authorization header
    r = await async_requests.get(
        public_url(app, mockservice_url) + '/whoami/',
        headers={'Authorization': f'token {no_access_token}'},
    )
    assert r.status_code == 403

    # token in Authorization header
    r = await async_requests.get(
        public_url(app, mockservice_url) + '/whoami/',
        headers={'Authorization': f'token {token}'},
    )
    r.raise_for_status()
    reply = r.json()
    sub_reply = {key: reply.get(key, 'missing') for key in ['name', 'admin']}
    assert sub_reply == {'name': u.name, 'admin': False}

    # token in ?token parameter is not allowed by default
    r = await async_requests.get(
        public_url(app, mockservice_url) + f'/whoami/?token={token}',
        allow_redirects=False,
    )
    assert r.status_code == 403
Test HubAuthenticated service with user API tokens
jupyterhub/tests/test_services_auth.py