Add Sign in with ChatGPT using Authorization Code with PKCE and OpenID Connect.
Sign in with ChatGPT is currently available to selected commercial partners
through a limited trial. To join the waitlist, contact your OpenAI
representative.
Add Continue with ChatGPT to your website using the OAuth 2.0 Authorization
Code flow with PKCE and OpenID Connect. Your backend exchanges the authorization
code, verifies the OpenAI ID token, associates the verified issuer, client ID, and
subject (sub) with an application account, and creates its own session.
A
Sign in to Acme
Welcome back. Choose how you'd like to continue.
OR
By continuing, you agree to Acme’s Terms and Privacy Policy.
The recommended labels are Continue with ChatGPT and Sign in with ChatGPT.
If your other sign-in options use an icon with a short label, you can use the
ChatGPT logo with ChatGPT as the label. Choose a style that fits your sign-in
page.
The following examples show the full-length labels in black and white.
An OpenAI client ID, typically beginning with oaiapp_.
An exact registered callback URL for each environment.
The OpenAI issuer and corresponding authorization, token, and JWKS endpoints.
Your registered token-endpoint authentication method and, for a confidential client, its client secret.
A backend that can hold short-lived transaction state and create secure application sessions.
OpenAI publishes its production OpenID Connect discovery document at
https://auth.openai.com/.well-known/openid-configuration. Load the issuer,
authorization_endpoint, token_endpoint, and jwks_uri values from that
document. The production configuration in this example is:
Replace the illustrative client ID and redirect URI with the values supplied for
your application. Require the ID token’s iss claim to exactly match the issuer
returned by discovery.
OpenAI supports both public and confidential clients. For a confidential client,
store OPENAI_CLIENT_SECRET in your server-side secret manager. Public clients
don’t receive or use a client secret. This guide covers
identity scopes; ChatGPT plan usage in open-source apps
has a separate authorization and registration flow.
Use a maintained OAuth or OpenID Connect library when possible. The examples
below show backend operations using Node’s crypto module and jose, or
Python’s secrets and hashlib modules, HTTPX, and PyJWT. The Go examples
use the standard library’s HTTP and cryptography packages and
github.com/golang-jwt/jwt/v5. The Java examples use
java.net.http.HttpClient, Jackson, and Auth0 java-jwt. The Ruby examples
use Net::HTTP, standard cryptography libraries, and the jwt gem. The C#
examples use .NET 10, HttpClient, and System.IdentityModel.Tokens.Jwt.
Wire them to your application routes and session store. The Python session
function returns an HTTPX response; send its status and headers through your
web framework’s response API. The Ruby session function returns a
Rack-compatible status, headers, and body tuple. The samples use in-memory
stores; production storage must expire transactions and support atomic,
one-time consumption across instances.
The C# excerpts form one WebsiteApplication class. Combine them in order, then create one instance for your application routes. The session method returns a cookie header; send it as Set-Cookie when redirecting to /app. Implement session lookup and revocation in your application’s session store.
The Ruby excerpts form one ChatGPTWebsiteSignIn class. Combine them in order: the final excerpt closes the class and creates application. Have your routes call methods on that instance.
1. Add the sign-in button
Point the button to your application’s sign-in route. In this example, implement
/auth/openai on your backend to create a sign-in transaction and redirect the
browser to OpenAI’s authorization endpoint. The following steps show how to
generate PKCE values and exchange tokens on the backend.
<a href="/auth/openai" data-oai-siwc-button data-oai-siwc-button-client="oaiapp_example"> Continue with ChatGPT</a>
Add the data-oai-siwc-button HTML attribute to each Sign in with ChatGPT
button or link on your page to help OpenAI verify your integration and
troubleshoot sign-in issues. Add the attribute directly to the clickable
element without a value. Optionally set data-oai-siwc-button-client to the
OAuth client ID used by that button or link.
Keep the button discoverable for new and returning users. Use approved OpenAI
branding and assets, with a clear, accessible label such as Continue with
ChatGPT.
2. Create a one-time sign-in transaction
Generate a fresh state, PKCE verifier, S256 challenge, and nonce on your backend.
Bind the transaction to a server-generated browser session identifier.
Include the following optional query parameters on the initial OpenAI
authorization URL to help troubleshoot sign-in issues. Use opaque IDs that you
can match to your application’s logs. These IDs do not expose the underlying
session or device data to OpenAI.
Store these values with the sign-in transaction so you can add them to the
authorization URL in the next step. The TypeScript example passes deviceToken,
loginSessionId, and loginStartedAtMs in the signInMetadata object. The Python
example stores the corresponding ext_ parameter names in sign_in_metadata.
The Go example stores those names in the transaction’s Metadata values.
The example expires transactions after 10 minutes. Store the browser session
identifier in an HttpOnly, Secure, SameSite=Lax cookie. Keep the verifier and
other transaction values server-side.
3. Redirect to OpenAI
Build the authorization URL on your backend, then redirect the browser to it.
Include the optional sign-in signals below to help troubleshoot sign-in issues.
They help you and OpenAI match an authorization request to your app’s device
and login session logs and identify when the user started signing in. This makes
it easier to investigate a specific sign-in attempt together.
Parameter
Type
Description
ext_device_token
String
An opaque identifier assigned by your app to the device. Reuse it for sign-in attempts from the same device.
ext_login_session_id
String
An opaque identifier for the app’s login session, used to match the sign-in request to your session logs.
ext_login_started_at_ms
Integer
The Unix timestamp in milliseconds when the user starts signing in to your app. OpenAI ignores values that aren’t valid.
The example adds these parameters when the transaction contains their values.
Send them in the authorization request, not the token exchange.
Receive available profile claims, such as a name or profile picture.
email
Receive available email and email-verification claims.
4. Handle the callback and verify state
Recover and consume the original transaction. Verify its expiration and returned
state, and check authorization errors before processing a code. Pass the
callback URL from the current request and the session identifier from the
browser’s secure cookie.
TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27exportfunctionconsumeSignInTransaction(browserSessionId:string,callbackUrl:URL) {consttransaction= transactions.get(browserSessionId); transactions.delete(browserSessionId);constreturnedState= callbackUrl.searchParams.get("state");if (!transaction || transaction.expiresAt <= Date.now() || returnedState !== transaction.state ) {thrownewError("Sign-in could not be verified."); }if (callbackUrl.searchParams.has("error")) {thrownewError("Sign-in could not be completed."); }constcode= callbackUrl.searchParams.get("code");if (!code) {thrownewError("The callback did not contain an authorization code."); }return { code, transaction };}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22def single_parameter(params, name): values = params.get(name, []) if len(values) != 1 or not values[0]: raise ValueError(f"Expected one nonempty {name} parameter") return values[0]def consume_sign_in_transaction(browser_session_id, callback_url): transaction = transactions.pop(browser_session_id, None) params = parse_qs(urlsplit(callback_url).query, keep_blank_values=True) returned_state = single_parameter(params, "state") if ( transaction is None or transaction.expires_at <= time.time() or not secrets.compare_digest( returned_state.encode(), transaction.state.encode() ) ): raise ValueError("Sign-in could not be verified") if "error" in params: raise ValueError("Sign-in could not be completed") return single_parameter(params, "code"), transaction
A missing, expired, reused, or mismatched transaction ends sign-in. Never redeem a
code from an unverified callback. Clear temporary browser state on success and
failure, and show an actionable sign-in error without exposing credentials.
5. Exchange the authorization code
Call the OpenAI token endpoint from your backend using the original redirect URI
and PKCE verifier. Use the token-endpoint authentication method provisioned for
your client.
Public client
An identity-only public client requests openid, profile, and email. It
authenticates at the token endpoint with none and doesn’t send a client secret.
If OpenAI provisioned a confidential client with client_secret_basic, use its
client secret to authenticate the backend token request. Keep PKCE in this flow.
Send the secret only through the HTTP Basic authorization header. Don’t add it to
the form body. A missing or invalid secret causes the request to fail; OpenAI
doesn’t fall back to public-client authentication. Never expose the secret in
client-side code, logs, URLs, agent output, or source control.
Validate the token response
After either request, check the response before using the returned ID token.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20public static string ReadIdentityToken(JsonElement tokens) => tokens.TryGetProperty("id_token", out JsonElement value) && value.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(value.GetString()) ? value.GetString()! : throw new ArgumentException("The response did not contain an ID token.");private static async Task<JsonElement> RequestJsonAsync(HttpRequestMessage request, TimeSpan timeout){ // One deadline covers headers and the complete body, including slow responses. using CancellationTokenSource deadline = new(timeout); using HttpClientHandler handler = new() { AllowAutoRedirect = false }; using HttpClient http = new(handler); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); using HttpResponseMessage response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, deadline.Token); if (!response.IsSuccessStatusCode) throw new HttpRequestException($"OpenAI OAuth request failed: HTTP {(int)response.StatusCode}."); await response.Content.LoadIntoBufferAsync(1_048_576, deadline.Token); using JsonDocument document = JsonDocument.Parse(await response.Content.ReadAsByteArrayAsync(deadline.Token)); return document.RootElement.Clone();}
1
2
3
4
5
6
7
8def read_identity_token(tokens) # request_json rejects non-success status codes without logging tokens. unless tokens.is_a?(Hash) && nonempty?(tokens["id_token"]) raise ArgumentError, "The token response did not contain an ID token" end tokens["id_token"]end
For standard identity-only sign-in, the required artifact is id_token. Don’t
require an OpenAI access_token or refresh_token; they aren’t part of the
standard identity-only client contract.
6. Verify the ID token
Verify the JWT signature against the issuer’s JWKS before trusting identity
claims. Check the issuer, audience, expiration, and original nonce. The TypeScript
example initializes jwks with createRemoteJWKSet from jose; Python uses
PyJWKClient from PyJWT. Both use the discovery document’s jwks_uri.
TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26exportasyncfunctionverifyOpenAiIdentity(idToken:string|Uint8Array<ArrayBufferLike>,expectedNonce:string) {const { payload } =awaitjwtVerify(idToken, jwks, { issuer, audience: clientId, requiredClaims: ["sub", "exp", "iat"], clockTolerance: 5, });if (payload.nonce !== expectedNonce) {thrownewError("The ID token nonce did not match."); }if (typeof payload.sub !=="string"||!payload.sub) {thrownewError("The ID token did not contain a subject."); }if ( payload.sid !==undefined&& (typeof payload.sid !=="string"||!payload.sid.trim()) ) {thrownewError("The ID token contained an invalid session identifier."); }return payload;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32def verify_openai_identity(id_token, expected_nonce): header = jwt.get_unverified_header(id_token) if ( header.get("alg") != "RS256" or not isinstance(header.get("kid"), str) or not header["kid"] ): raise jwt.InvalidTokenError("Invalid ID token signing header") key = jwks.get_signing_key_from_jwt(id_token) identity = jwt.decode( id_token, key.key, algorithms=["RS256"], issuer=ISSUER, audience=CLIENT_ID, options={"require": ["iss", "aud", "sub", "exp", "iat", "nonce"]}, leeway=5, ) nonce = identity.get("nonce") if not isinstance(nonce, str) or not secrets.compare_digest( nonce.encode(), expected_nonce.encode() ): raise jwt.InvalidTokenError("The ID token nonce did not match") if not isinstance(identity["sub"], str) or not identity["sub"].strip(): raise jwt.InvalidTokenError("The ID token did not contain a subject") if "sid" in identity and ( not isinstance(identity["sid"], str) or not identity["sid"].strip() ): raise jwt.InvalidTokenError( "The ID token contained an invalid session identifier" ) return identity
Use a maintained JWT library, allow only a small clock-skew tolerance, cache JWKS
responsibly, and refresh keys when an unfamiliar kid appears. This example
always sends a nonce and requires the same value in the ID token.
Email availability and verification
When you request the email scope, successful website sign-ins are currently
expected to include email and email_verified: true. If the user’s email is
missing or unverified, OpenAI prompts the user to provide or verify an email
address with a one-time code before completing sign-in.
Requesting the email scope does not guarantee that the ID token includes an
email claim or that email_verified is true. Your application must handle
a missing email claim and an email_verified claim that is false or absent.
Treat an email as verified only when email is nonempty and email_verified is
the boolean true. If your application requires a verified email, collect and
verify it when these conditions are not met.
Sample ID token
This decoded ID token illustrates the unverified-email case that your application
must still handle:
Issuer: the OpenAI auth server that issued the token.
sub
User ID: identifies the OpenAI user to your app.
aud
Audience: the client ID of the app that should receive this token.
nonce
Sign-in request reference: matches the value your app sent when starting sign-in.
auth_time
Authentication time: when the user authenticated, in Unix seconds.
email
The user’s email address.
email_verified
Whether OpenAI has verified the email address.
name
The user’s display name.
sid
OpenAI session reference: an opaque ID, separate from the partner-provided ext_login_session_id.
https://api.openai.com/auth
A container for OpenAI-specific fields.
per_user_salt
A nested field in https://api.openai.com/auth that OpenAI uses to generate anonymous identifiers. Treat this value as opaque.
iat
Issued at: when OpenAI created the token, in Unix seconds.
exp
Expires at: when the token expires, in Unix seconds.
jti
Token ID: uniquely identifies this token.
at_hash
Access-token hash: checks that an accompanying access token matches this ID token, if OpenAI issues one.
7. Find, create, or link the local account
Use the verified OpenAI sub as the stable external identity. Include the issuer
and client to prevent collisions across providers and environments. Store this
mapping and look it up before matching by email, so returning users keep the
same account if their email address changes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24public record IdentityKey(String issuer, String clientId, String subject) {}public static Map<String, Object> externalIdentityFor(DecodedJWT identity) { Map<String, Object> external = new LinkedHashMap<>(); external.put("provider", "openai"); external.put("issuer", ISSUER); external.put("client_id", CLIENT_ID); external.put("subject", identity.getSubject()); for (String name : new String[] {"email", "name", "picture"}) external.put(name, identity.getClaim(name).asString()); return external;}public static synchronized String findLinkedAccount(DecodedJWT identity) { return ACCOUNTS.get(new IdentityKey(ISSUER, CLIENT_ID, identity.getSubject()));}public static synchronized void linkAccount(DecodedJWT identity, String localUserId) { // Call only with a verified identity, an authenticated local user, and explicit linking // consent. if (localUserId == null || localUserId.isBlank()) throw new IllegalArgumentException("Missing local user"); ACCOUNTS.put(new IdentityKey(ISSUER, CLIENT_ID, identity.getSubject()), localUserId);}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21public string? FindLinkedAccount(JwtSecurityToken verifiedIdentity){ lock (gate) return accounts.GetValueOrDefault(verifiedIdentity.Subject);}public void LinkAccount(JwtSecurityToken verifiedIdentity, string authenticatedLocalUserId, bool consentGranted){ // Only pass the token returned by VerifyIdentityAsync, after the host // authenticates the local account and verifies its consent POST's CSRF token. ArgumentException.ThrowIfNullOrWhiteSpace(authenticatedLocalUserId); if (!consentGranted) throw new ArgumentException("Account-linking consent is required."); lock (gate) { string? existing = accounts.GetValueOrDefault(verifiedIdentity.Subject); if (existing is not null && existing != authenticatedLocalUserId) throw new InvalidOperationException("Identity is already linked."); if (existing is null && accounts.Count >= 1024) throw new InvalidOperationException("Account store is full."); // This store is scoped to the fixed issuer and client above. Never merge by email. accounts[verifiedIdentity.Subject] = authenticatedLocalUserId; }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28def external_identity_for(identity) { provider: "openai", issuer: ISSUER, client_id: CLIENT_ID, subject: identity.fetch("sub"), email: identity["email"], name: identity["name"], picture: identity["picture"] }enddef find_linked_account(identity) @lock.synchronize { @accounts[[ISSUER, CLIENT_ID, identity.fetch("sub")]] }enddef link_account(identity, local_user) # Only call after verification and explicit account-linking consent. # Never select or merge accounts using the email claim alone. @lock.synchronize do key = [ISSUER, CLIENT_ID, identity.fetch("sub")] if @accounts.key?(key) && @accounts[key].fetch("id") != local_user.fetch("id") raise ArgumentError, "Identity is already linked" end @accounts[key] = local_user.dup.freeze endend
Apply an explicit account-linking policy:
If the OpenAI subject is already linked, sign in to the linked local account.
If the subject isn’t linked and the verified ID token has email_verified: true, you can use a matching email address to link and sign in to an existing local account. Store the OpenAI identity mapping for future sign-ins.
If a signed-in user adds ChatGPT as a sign-in method, provide a way to confirm and link the accounts. If email_verified is false or absent, require your existing account-ownership verification before linking by email.
If no account exists, allow account creation according to your product, onboarding, and enterprise policies.
8. Create your application session
After verification and account resolution, issue your own first-party session.
The helper below receives your HTTP response, the resolved local user, and the
verified ID-token claims. It stores the issuer, client ID, subject, and optional
sid with the app session so you can identify sessions affected by an
account security notification.
Use an HttpOnly, Secure, SameSite=Lax session cookie. Don’t return an ID token,
PKCE verifier, or client secret to browser JavaScript. Clear
the temporary sign-in cookie after completing the transaction.
Retain only the identity mapping and user information your application needs.
Avoid storing raw OpenAI ID tokens after verification unless a separately
documented requirement demands it.
Test before launch
Confirm the registered callback and requested redirect_uri match exactly.
Generate fresh state, PKCE values, and a nonce for every sign-in.
Check that missing, expired, reused, and mismatched transaction state is rejected.
Exchange the code with the original verifier and registered client authentication method.
Check that a confidential token request with a missing or invalid secret fails.
Check that an ID token with an invalid signature, issuer, audience, expiration, or nonce is rejected.
Clear temporary authorization state after success and failure.
Confirm that signing out clears only the first-party application session.