Skip to content

Getting a token

Every call to the Public API carries a short-lived token from WorkOS, the platform's identity provider. How your application gets that token depends on one question: is a person signed in? This page walks through the setup for each answer. Authentication explains what the tokens contain and why the platform works this way.

Your application Flow Working example
A website with a server side (Next.js, a BFF) AuthKit, authorization code The Content Lake console
A CLI or native app with no server of its own Device authorization grant The packt CLI
A service, job or integration with no person involved Client credentials (M2M) tools/m2m-demo in the monorepo

All three use the Packt Platform WorkOS environment:

Setting Value
Environment client ID client_01KT18NR5C5DKT5G52XT36KHAM
Sign-in API (people) https://api.workos.com/user_management/…
Token endpoint (services) https://identity.packtpub.services/oauth2/token
Public API https://api.packtpub.services

Check your token: /v0/caller

Whatever the flow, finish by calling GET /v0/caller. It needs a token but no scope, and answers with what the Public API made of it:

curl -s -H "Authorization: Bearer $TOKEN" \
  https://api.packtpub.services/v0/caller
{
  "subject": "client_01M6EEWG4JN2KC7HTVWB5ZD6CZ",
  "kind": "application",
  "tenantId": "packt",
  "clientId": "client_01M6EEWG4JN2KC7HTVWB5ZD6CZ",
  "scopes": []
}

A 200 here means authentication works. Other routes can still refuse the token: most need a scope, and a route that names a resource checks that the resource belongs to the token's tenant. A 401 names the reason (TOKEN_MISSING, TOKEN_INVALID, TOKEN_EXPIRED) in the problem body.

A website: sign people in with AuthKit

The site sends people to WorkOS's hosted sign-in page, receives a one-time code on its callback URL, and exchanges it for tokens on the server. The session lives in an encrypted cookie on your domain; the browser never sees the access token.

  1. Register the callback URL. In the WorkOS dashboard, in the Packt Platform environment, add https://<your-site>/callback under Redirects, plus http://localhost:3000/callback for development.
  2. Configure the server. It needs four settings:

    Variable Value
    WORKOS_CLIENT_ID The environment client ID
    WORKOS_API_KEY An API key for the environment. It is a secret: server side only.
    WORKOS_COOKIE_PASSWORD 32 or more random characters, to encrypt the session cookie
    NEXT_PUBLIC_WORKOS_REDIRECT_URI The callback URL from step 1
  3. Wire up AuthKit. With @workos-inc/authkit-nextjs, mount the callback route and run AuthKit in the proxy (middleware), which keeps the session refreshed:

    app/callback/route.ts
    import { handleAuth } from '@workos-inc/authkit-nextjs';
    
    export const GET = handleAuth({ returnPathname: '/' });
    
  4. Call the API from the server. Read the access token from the session and send it as the bearer:

    import { withAuth } from '@workos-inc/authkit-nextjs';
    
    const { accessToken } = await withAuth({ ensureSignedIn: true });
    const res = await fetch('https://api.packtpub.services/v0/caller', {
      headers: { Authorization: `Bearer ${accessToken}` },
    });
    

A person's token is scoped to the organisation they signed in to. A person who belongs to several organisations picks one at sign-in, on AuthKit's organisation picker.

A CLI or native app: the device grant

An app on someone's machine has nowhere to receive a redirect and cannot keep a secret, so it holds only the client ID and lets the person approve the sign-in in their browser.

  1. Start the sign-in. Post the client ID:

    curl -s https://api.workos.com/user_management/authorize/device \
      -d client_id=client_01KT18NR5C5DKT5G52XT36KHAM
    

    The reply carries a user_code and a verification_uri_complete to show the person, a device_code to keep, and a polling interval in seconds.

  2. Poll for the tokens every interval seconds while the person approves:

    curl -s https://api.workos.com/user_management/authenticate \
      -d grant_type=urn:ietf:params:oauth:grant-type:device_code \
      -d device_code="$DEVICE_CODE" \
      -d client_id=client_01KT18NR5C5DKT5G52XT36KHAM
    

    authorization_pending means keep waiting; slow_down means add five seconds to the interval. Success returns an access_token and a refresh_token.

  3. Refresh before expiry. Post grant_type=refresh_token with the refresh token and the client ID to the same endpoint. Store both tokens where only the signed-in user can read them.

The packt CLI's cli/internal/session/workos.go is a complete implementation in Go, with no WorkOS SDK.

A service: client credentials

A service acting as itself — a scheduled job, an integration, another system calling the platform — has no person to sign in. It holds the client ID and secret of a WorkOS M2M application and exchanges them for a token.

  1. Create the application. In the WorkOS dashboard, in the Packt Platform environment, create an M2M application and link it to one organisation: the tenant it acts in. Acting in two tenants takes two applications.
  2. Store the secret. Keep the client ID in configuration and the secret in your secret store. Neither goes in source control.
  3. Check the organisation's external ID. The Public API reads the tenant from it, so it must be the tenant ID. The platform sets it when it creates a tenant, so an existing tenant's organisation already has one. There is nothing else to register: creating the application on the organisation is the grant. While the external ID is empty, the API refuses the application's tokens with TOKEN_INVALID.
  4. Get a token and call the API. Any OAuth 2 client-credentials library works. In Go:

    cfg := clientcredentials.Config{
        ClientID:     os.Getenv("WORKOS_CLIENT_ID"),
        ClientSecret: os.Getenv("WORKOS_CLIENT_SECRET"),
        TokenURL:     "https://identity.packtpub.services/oauth2/token",
        AuthStyle:    oauth2.AuthStyleInHeader,
    }
    client := cfg.Client(ctx) // fetches, caches and renews the token
    resp, err := client.Get("https://api.packtpub.services/v0/caller")
    

    Or by hand:

    curl -s https://identity.packtpub.services/oauth2/token \
      -u "$WORKOS_CLIENT_ID:$WORKOS_CLIENT_SECRET" \
      -d grant_type=client_credentials
    

    Reuse the token until shortly before it expires rather than asking for one on every request. How WorkOS grants scopes to an M2M application is still being confirmed; /v0/caller shows which scopes your token carries.

To prove a new application end to end, run the demo from the monorepo root. It prints each step — the token exchange, the decoded claims, the API's answer — and never prints the secret:

WORKOS_CLIENT_ID=client_01… WORKOS_CLIENT_SECRET=… \
  go run ./tools/m2m-demo

When the API says TOKEN_INVALID

The likeliest cause for a new application is an organisation with no external ID. Run the demo with --verify (and a WorkOS API key in WORKOS_API_KEY, if you have one): it checks the token exactly as the Public API does and names the organisation or claim at fault.

invalid_client from WorkOS

WorkOS answers the same way for a wrong client ID, a wrong secret, and an application in a different environment. Check all three.