Launch offer for the first 500 accounts: $10K MTR free for 24 months + $100 credit →
    .io

    Auth Quickstart

    What you will have at the end

    A working password sign-in on the web, a session that survives a page reload when the page is served from your hosted auth domain, and a Node route that verifies the token and reads the user's entitlements without calling BillDog. Roughly fifteen minutes.

    1. Turn auth on

    Project Settings → Auth → Enable authentication. Auth is off by default and every endpoint answers 403 ACCESS_DENIED until it is on — if your first call fails that way, this is the step you skipped.

    Three things have to be true first, and each one fails somewhere far from its cause, so it is worth doing them in this order:

    • An email provider, under Messaging. Verification codes go out through yours, not ours. Without one the Enable switch stays disabled — the server refuses the change and so does the database.
    • A US data region. Auth credentials may only be stored in the US. On any other region enabling is refused outright, and there is no workaround today. The Auth tab says so before you try.
    • Signing keys. Turning auth on does not mint them. Press Provision on the Auth tab, which creates one key per environment. Skip it and sign-in answers 500 No signing key is provisioned, which reads like an outage and is really a missing step.

    Leave the rest at its defaults for now: access mode open, no captcha, no MFA mandate, an eight-character password minimum with the breach check on.

    2. Install and create the client

    # Pin the exact version. Neither "latest" nor the "beta" dist-tag is a safe
    # install for a pre-release: both are mutable pointers, and one pointing at an
    # older build is how you end up with an SDK that is missing half this page.
    npm install @billdog.io/auth@1.2.0-beta.1
    auth.ts
    import { createBillDogAuth } from '@billdog.io/auth';
    
    export const auth = createBillDogAuth({
      // Your PUBLIC key. It ships in the browser — that is what it is for.
      apiKey: 'bd_public_live_…',
      onSessionChange: (session) => {
        // Fires on sign-in, on refresh, and on expiry. Render from here.
        console.log(session ? 'signed in' : 'signed out');
      },
    });

    The key's prefix picks the environment. bd_public_test_… reaches your sandbox, whose users are entirely separate people from production's.

    3. Restore the session on load

    Do this before you render anything that depends on who is signed in. It returns null on a first visit, which is an ordinary state and not an error. On your hosted domain a load that cannot reach the server also returns null, and the SDK keeps trying: listen with onSessionChange rather than treating that first answer as final.

    Reloads survive only on your hosted auth domain. There the refresh token is a first-party httpOnly cookie that restore() uses. On any other origin (for example localhost against the default API host) the SDK holds the refresh token in memory only, so after a reload restore() returns null and the user signs in again. See Sessions and tokens.

    Code
    const session = await auth.restore();
    if (session) {
      // Already signed in — skip the form.
    }

    4. Sign someone up

    Sign-up never issues a session. It sends a code, and attempt with that code is what finishes the job. That is deliberate: an unverified address must not become a live account.

    Code
    await auth.signUp({
      identifier: 'ada@example.com',
      password: 'a-long-passphrase',
    });
    // -> { verificationRequired: true }   always
    
    // They read the emailed code, then:
    const { session } = await auth.attempt({
      identifier: 'ada@example.com',
      strategy: 'email_code',
      code: '123456',
    });

    The answer is identical whether or not the address was already registered. That is not a quirk to work around — telling the two apart is an account-enumeration oracle, so no BillDog endpoint will ever do it. A sign-up that was accepted but never finished — the code never verified, no password stored — can simply be repeated: the same call resumes it and sends a fresh code. And a password the policy refuses answers 400 naming the rule, before anything is written, so a refusal leaves no half-made account behind.

    5. Sign someone in

    Code
    const result = await auth.attempt({
      identifier: 'ada@example.com',
      strategy: 'password',
      password,
    });
    
    // ALWAYS check this first. Against an account with a second factor, a correct
    // password issues NO session — result.session is null and this is true.
    if (result.mfaRequired) {
      const done = await auth.attempt({
        strategy: 'totp',
        code: authenticatorCode,
        mfaToken: result.mfaToken,   // proves the password was already accepted;
                                     // no identifier needed — the token names the account
      });
      use(done.session);
    } else {
      use(result.session);
    }

    6. Use the session

    authHeaders() emits X-BillDog-Session, not Authorization: Bearer. Read that header on your backend, or copy the value into whichever header your framework already expects — step 8 verifies the token itself, and does not care how it arrived.

    Code
    // Your own API calls
    await fetch('/api/thing', { headers: auth.authHeaders() });
    
    // Or hand the token to the BillDog client once
    auth.attachTo(billdog.apiClient);
    
    // Ending it
    await auth.signOut();        // this device
    await auth.signOut('all');   // everywhere

    7. Reset or change a password

    A reset is two calls and needs no session — the emailed code is the proof. It signs every device out and issues nothing; the person signs in again with the new password. A change is one call from a signed-in device, proves the current password, and keeps this session while revoking the others.

    Code
    // Forgot password
    await auth.requestPasswordReset({ identifier: 'ada@example.com' });
    await auth.resetPassword({
      identifier: 'ada@example.com',
      code: '123456',                       // from the email
      newPassword: 'a-new-long-passphrase',
    });
    // -> { updated: true, sessionsRevoked }   then sign in again
    
    // Change password, while signed in
    await auth.changePassword({ currentPassword, newPassword });
    // -> still signed in here; every OTHER session was ended

    The same two flows exist on every SDK, and a hosted wall has both built in — reset on the wall, change on its /account portal. See Passwords.

    8. Verify it on your backend

    This is the half that matters. Verification is a local signature check against a cached key set — no network call on your request path, so an outage on our side cannot take your authorization down with it.

    Node
    import { verifyToken, hasEntitlement } from 'billdogeng-node';
    
    const claims = await verifyToken(bearerToken, {
      projectId: process.env.BILLDOG_PROJECT_ID!,
      environment: 'production',   // defaults to production; see below
    });
    
    claims.sub;   // the user — who signed in
    claims.cus;   // the customer — what they own, for joining BillDog data
    
    if (!hasEntitlement(claims, 'pro')) return res.status(403).end();

    When it does not work

    What you seeWhat it usually is
    403 ACCESS_DENIEDAuth is not enabled on the project. Step 1.
    500 "No signing key is provisioned."Auth is on but no key was minted, or none for this environment. Press Provision on the Auth tab — it creates one per environment.
    401 INVALID_API_KEYWrong key, or a secret key where a public one belongs.
    401 "The credentials provided are not valid."Every credential failure looks like this, on purpose. Wrong password, unknown user, expired code, locked account — one answer.
    400 on sign-upThe password missed the policy (the message names the rule), or the project needs a captcha or an invitation you did not send — call auth.config() to find out which. Nothing was written either way; try again.
    429Three factor submissions per identifier per ten seconds. Back off.
    Signed in, then signed out ~90 s laterYou are holding the token yourself instead of letting the SDK refresh it, or you never called restore().

    Next

    Was this page helpful?

    Or rate this page:

    We use cookies and process your data to provide our services. By continuing, you agree to our Terms and Privacy Policy.