Hub documentation
Adding a Sign-In with HF button to your Space
Adding a Sign-In with HF button to your Space
You can enable a built-in sign-in flow in your Space by seamlessly creating and associating an OAuth/OpenID connect app so users can log in with their HF account.
This enables new use cases for your Space. For instance, when combined with Storage Buckets, a generative AI Space could allow users to log in to access their previous generations, only accessible to them.
This guide will take you through the process of integrating a Sign-In with HF button into any Space. If you’re seeking a fast and simple method to implement this in a Gradio Space, take a look at its built-in integration.
You can also use the HF OAuth flow to create a “Sign in with HF” flow in any website or App, outside of Spaces. Read our general OAuth page.
Create an OAuth app
All you need to do is add hf_oauth: true to your Space’s metadata inside your README.md file.
Here’s an example of metadata for a Gradio Space:
title: Gradio Oauth Test
emoji: 🏆
colorFrom: pink
colorTo: pink
sdk: gradio
sdk_version: 3.40.0
python_version: 3.10.6
app_file: app.py
hf_oauth: true
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
hf_oauth_expiration_minutes: 480
# optional, see "Scopes" below. "openid profile" is always included.
hf_oauth_scopes:
- read-repos
- gated-repos
- write-repos
- manage-repos
- inference-api
# optional, restrict access to members of specific organizations
hf_oauth_authorized_org: ORG_NAME
hf_oauth_authorized_org:
- ORG_NAME1
- ORG_NAME2You can check out the configuration reference docs for more information.
This will add the following environment variables to your space:
OAUTH_CLIENT_ID: the client ID of your OAuth app (public)OAUTH_CLIENT_SECRET: the client secret of your OAuth app (deprecated: use PKCE instead which doesn’t need the secret for the token exchange)OAUTH_SCOPES: scopes accessible by your OAuth app.OPENID_PROVIDER_URL: The URL of the OpenID provider. The OpenID metadata will be available at{OPENID_PROVIDER_URL}/.well-known/openid-configuration.
Every Space also gets a SPACE_SIGNING_SECRET, a stable per-Space secret. Use PKCE for the token exchange, and use SPACE_SIGNING_SECRET to sign your own session cookies so that logins survive restarts and are shared across replicas.
As for any other environment variable, you can use them in your code by using os.getenv("OAUTH_CLIENT_ID"), for example.
Redirect URLs
You can use any redirect URL you want, as long as it targets your Space.
Note that SPACE_HOST is available as an environment variable.
For example, you can use https://{SPACE_HOST}/login/callback as a redirect URI.
Scopes
The following scopes are always included for Spaces:
openid: Receive an ID token in addition to the access token.profile: Read the user’s profile information (username, avatar, etc.)
Those scopes are optional and can be added by setting hf_oauth_scopes in your Space’s metadata:
email: Read the user’s email address.read-billing: Know whether the user has a payment method set up.read-memberships: Read which organizations the user belongs to, and their role in each of them. This does not grant access to the organizations’ settings or resources.read-repos: Read the user’s personal repos.gated-repos: Read the content of public gated repos the user has been granted access to. Unlikeread-repos, this does not grant access to private repos.request-gated-repos: Request access to gated repos on behalf of the user. The user’s profile is shared with the repo authors as part of the request, according to the repo’s gating settings.contribute-repos: Create repositories and access those created by this app. Cannot access any other repositories unless additional permissions are granted.write-repos: Read and write the user’s personal repos.manage-repos: Fully manage the user’s personal repos, including creating and deleting them.read-collections: Read the user’s personal collections.write-collections: Read and write the user’s personal collections, including creating and deleting them.inference-api: Make inference requests to Inference Providers on behalf of the user.read-endpoints: View the user’s Inference Endpoints and make inference requests to them on behalf of the user.write-endpoints: Manage the user’s Inference Endpoints, including creating and deleting them. Includesread-endpointsaccess.jobs: Run jobswebhooks: Manage webhookswrite-discussions: Open discussions and Pull Requests on behalf of the user as well as interact with discussions (including reactions, posting/editing comments, closing discussions, …). To open Pull Requests on private repos, you need to request theread-reposscope as well.
Accessing organization resources
By default, the oauth app does not need to access organization resources.
But some scopes like read-repos or read-billing apply to organizations as well.
The user can select which organizations to grant access to when authorizing the app. If you require access to a specific organization, you can add orgIds=ORG_ID as a query parameter to the OAuth authorization URL. You have to replace ORG_ID with the organization ID, which is available in the organizations.sub field of the userinfo response.
Adding the button to your Space
You now have all the information to add a “Sign-in with HF” button to your Space. Some libraries (Python, NodeJS) can help you implement the OpenID/OAuth protocol.
Gradio and huggingface.js also provide built-in support, making implementing the Sign-in with HF button a breeze; you can check out the associated guides with gradio and with huggingface.js.
Basically, you need to:
- Redirect the user to
https://huggingface.co/oauth/authorize?redirect_uri={REDIRECT_URI}&scope=openid%20profile&client_id={CLIENT_ID}&state={STATE}&code_challenge={CODE_CHALLENGE}&code_challenge_method=S256, whereSTATEis a random string that you will need to verify later andCODE_CHALLENGEis the base64url-encoded SHA-256 hash of a randomcode_verifier(PKCE). - Handle the callback on
/auth/callbackor/login/callback(or your own custom callback URL) and verify thestateparameter. - Use the
codequery parameter to get an access token and id token fromhttps://huggingface.co/oauth/token(POST request withclient_id,code,grant_type=authorization_codeandredirect_uriandcode_verifieras form data). If your app has a client secret, also sendAuthorization: Basic {base64(client_id:client_secret)}as a header.
You should use
target=_blankon the button to open the sign-in page in a new tab, unless you run the space outside itsiframe. Otherwise, you might encounter issues with cookies on some browsers.
Examples:
- Gradio test app
- HuggingChat (NodeJS/SvelteKit)
- Inference Widgets (Auth.js/SvelteKit), uses the
inference-apiscope to make inference requests on behalf of the user. - Client-Side in a Static Space (huggingface.js) - very simple JavaScript example.
JS Code example:
import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub";
const oauthResult = await oauthHandleRedirectIfPresent();
if (!oauthResult) {
// If the user is not logged in, redirect to the login page
window.location.href = await oauthLoginUrl();
}
// You can use oauthResult.accessToken, oauthResult.userInfo among other things
console.log(oauthResult);