Is there a way to create a REST API token with user's OAuth token through REST API

Hi Jovyans,

  • Jupyterhub version: 1.4.2
  • Authenticator: GenericOAuthenticator
  • Issue: Need to call REST API(/users//server) to start user server, this requires an user’s API token. I’ve been blocked with ‘how to create an API token for an user through a REST API’

I’m able to manually create an user’s API token on the browser, and then use that token to start an user’s server:

curl -X POST https://******/hub/api/users/<username>/server \
-H 'Authorization: token <manually created API token from the browser>' \
-H 'accept: application/json' \
--data-raw '{"profile":"<project_name>"}'

And now I need to call a REST API to generate an API token, then I found this one:

curl -X POST https://********/hub/api/oauth2/token -H 'Authorization: Bearer <OAuth token after login>' -H "Content-Type: application/x-www-form-urlencoded"

It seems like it won’t take an existing OAuth token, what is the right way to create an API token with OAuth token?

Found this old post here answered by @manics , and it says If you’re writing a custom UI you’ll need to implement authentication with Keycloak there, and give your front-end a privileged token that allows it to create tokens for users.

I guess there is not a solution to make REST API call with OAuth token… so we have to pre-generate a super-user token when deploying jupyterhub and use that super-user token to generate user’s API token…

Ended up, made an admin service doc for front-end to start user’s server, not the best practice for security… Let me know if there is a better way

Yes, you can create tokens via the REST API, the endpoint is /hub/api/users/:username/tokens, more info here. The requesting token needs the tokens scope for the user.

You’ll also want to upgrade juptyerhub to at least 3.0 for this. 1.4.2 is a couple of years behind.

Thanks @minrk ,
I understand 1.4.2 is pretty behind… and the upgrading work is ongoing.

I’ve tried hub/api/users/<username>/tokens with:

curl -X POST https://********/hub/api/users/<userA>/token -H 'Authorization: Bearer <userA's OAuth token after login>' -H "Content-Type: application/x-www-form-urlencoded"

then I got a 403 forbidden error.

Prior to JupyterHub 2’s introduction of roles and scopes, oauth tokens don’t have permission to do anything other than identify users. They cannot issue new tokens or make other API requests. So if you want to use tokens to issue tokens, you need to upgrade JupyterHub. Otherwise, an admin service like you’ve described is the way to go.

1 Like

Thanks for your information! That’s the confirmation I need, we added an extra API on our existing API server calling Jupyterhub API server to generate a user API token with the admin token.
But, yeah, the ultimate solution would be update Jupyterhub and use RBAC+OAuth.

1 Like