# Block-Auth Documentation > Block-Auth is passwordless login for your app with a decentralized identity. Your frontend opens the Block-Auth login (a widget for React, Vue or Angular, or a redirect from your backend, or the WordPress plugin), and your backend redeems a one-time code with its API Secret to get a verified user and create its own session. Every page is also available as plain Markdown: add `.md` to its path (for example `/sdk-integration.md`; the home page is `/index.md`). In the Markdown versions, every tab, framework, backend, environment and option that the website shows one at a time is written out in full. This index links to the Markdown versions. If you are an AI coding assistant implementing Block-Auth in an app, start with the [Integration checklist](/sdk-integration-checklist.md). It has the decision tree, the required steps in order, the security rules and the definition of done. --- title: "Block-Auth Documentation" description: "Passwordless login for your app with a decentralized identity. Your backend gets a verified user and keeps its own session." url: "/" language: "en" --- # Block-Auth Block-Auth lets people sign in to your app without passwords, with a decentralized identity they control. Your backend gets a verified user from Block-Auth and keeps its own session, its own users and its own rules. ## How it works 1. **The user signs in on Block-Auth.** Your app opens the Block-Auth login at `auth.block-auth.io`, in a popup or with a redirect. The user signs in with their Block-Auth identity, from the browser extension or the mobile app, or with Google, Microsoft, MetaMask, Phantom or WalletConnect, and approves the session. 2. **Your backend gets the user.** Block-Auth hands back a one-time code. Your backend redeems it with your API secret at `POST /api/auth/token` and receives the user's address and roles. The browser never decides who the user is. 3. **Your app keeps its session.** Your backend creates its own session, as with any other login method, and can link the Block-Auth user to a user you already have. Every session is signed on Block-Auth's blockchain, and your users can see and close their sessions, devices and linked apps in Block-Auth Identity. ## Explore the architecture Pick your stack to see the pieces you use in your code and how they connect to Block-Auth. Hover over a piece or a step to follow it. The two login flows, step by step. On the website this is an interactive diagram. **React, Vue, Angular (+ backend), widget in a popup:** 1. Your frontend → Block-Auth: Login in a popup (PKCE) 2. Block-Auth → Your frontend: One-time code 3. Your frontend → Your backend: `POST /code` 4. Your backend → Block-Auth: `POST /api/auth/token` 5. Block-Auth → Your backend: `{ address, roles }` 6. Your backend → Your frontend: httpOnly session cookie 7. Your frontend → Your backend: `GET /me` 8. Your backend → Your frontend: `{ address, roles }` **PHP, Python, .NET, Node.js, and WordPress (redirect login):** 1. Your pages → Your backend: `GET /blockauth/login` 2. Your backend → Block-Auth: `POST /api/auth/authorize` 3. Your backend → Your pages: Redirect to the login 4. Your pages → Block-Auth: The user signs in 5. Block-Auth → Your pages: Back with ?code\&state 6. Your pages → Your backend: `GET /blockauth/callback` 7. Your backend → Block-Auth: `POST /api/auth/token` 8. Block-Auth → Your backend: `{ address, roles }` 9. Your backend → Your pages: Session cookie and redirect ## What you get - **Passwordless login** with social accounts, wallets and the Block-Auth extension, on a login page Block-Auth hosts and maintains. - **Account linking** between a Block-Auth identity and the users you already have, without sharing your database. - **Roles** you define in the Dashboard, returned with every login. - **Signed webhooks** when a user signs out (`signout`) or unlinks your app (`account.unlinked`). - **SDKs** for React, Vue and Angular, for PHP, Python and .NET, and a WordPress plugin. --- title: "Getting Started" description: "The four steps from zero to Block-Auth working in your app." url: "/getting-started/" language: "en" --- # Getting Started These are the four steps from zero to Block-Auth working in your app. Follow them in order: each one needs the previous one. ## Your path 1. [Create your identity](/extension-quickstart.md): With the browser extension or the mobile app. You use it to sign in everywhere. 2. [Sign in to the Dashboard](/dashboard-quickstart.md): Use that same identity, no passwords. 3. [Prepare your app](/integration-quickstart.md): Register your app, get your keys and test on localhost before going live. 4. [Integrate your SDK](/sdk-integration.md): Follow the guide for your stack: React, Vue, Angular; PHP, Python, .NET, Node.js; or WordPress. --- title: "Browser Extension Documentation" description: "The Block-Auth browser extension: your identity, your sessions and passwordless sign-in from Chrome and Firefox." url: "/extension-introduction/" language: "en" --- # Block-Auth Browser Extension The Block-Auth extension serves as your secure gateway to Web3 and decentralized identity. It empowers users to manage credentials, sign cryptographic messages, and authenticate across applications without passwords, all directly from the browser with complete privacy control. [Go to Quickstart](/extension-quickstart.md) [Chrome Web Store](https://chromewebstore.google.com/detail/block-auth-one/jhjjpmjhiamddbfhogknjibkacajkpdg) [Firefox Add-ons](https://addons.mozilla.org/firefox/addon/block-auth-one/) ## Quickstart sections - [Sign Up](/extension-quickstart.md#how-to-create-an-account): Learn how to create an account using the BlockAuth extension. - [Sign In](/extension-quickstart.md#how-to-sign-in): Learn how to sign in to an account using the BlockAuth extension. --- title: "Block-Auth Extension Quickstart" description: "This guide will get you all set up and ready to use the Block-Auth Extension. We'll cover how to get started using browser extension." url: "/extension-quickstart/" language: "en" --- # Quickstart This guide will get you all set up and ready to use the Block-Auth Extension. We'll cover how to create an account and how to use the extension to authenticate and sign transactions. ## How to Create an Account To begin using the BlockAuth ecosystem, you first need to set up your identity through our browser extension. Follow these steps to create your secure decentralized account: ### 1. Download the extension Start by downloading the official Block-Auth extension for Chrome or Firefox. ### 2. Open the extension and select account type Launch the extension from your browser's toolbar. You will be presented with the account type selection screen. For this integration guide, select **"I am a business"**. This setup ensures you have the appropriate permissions for development and application management. _Screenshot: Extension account type selection screen_ ### 3. Secure your seed phrase Download and securely store your **Seed Phrase**. This file is the only way to recover your account if you lose access to your device. Once saved, accept the terms and privacy policy to continue. _Screenshot: Extension seed phrase backup screen_ ### 4. Identity validation (OTP) To add an extra layer of security, you must configure a One-Time Password (OTP) using applications like **Google Authenticator**, **Authy**, or **Microsoft Authenticator**. Scan the QR code with your chosen app and enter the generated 6-digit code. _Screenshot: Extension OTP identity validation screen_ ### 5. Finalize setup Your account is now ready! Clicking **"Finish"** will automatically redirect you to **BlockAuth Identity**. While you can complete your full profile registration there, please note that it is optional for the SDK integration process. _Screenshot: Extension setup completion screen_ --- title: "Dashboard Introduction" description: "Learn everything there is to know about the Block-Auth Dashboard and how to use it." url: "/dashboard-intro/" language: "en" --- # Block-Auth Dashboard The Dashboard is where your company manages Block-Auth: your apps and their keys, your users and their roles, your app's activity, your team and billing. You sign in with your Block-Auth identity, the one you created with the extension or the mobile app. [Go to Quickstart](/dashboard-quickstart.md) [Register your app](/integration-quickstart.md) ## Next steps - [Sign in to the Dashboard](/dashboard-quickstart.md#sign-up): Use your Block-Auth identity, no passwords. - [Register your app](/integration-quickstart.md#applications): Register your app, get your keys and test on localhost before going live. - [Roles](/dashboard-roles.md): Create roles and assign them to your users. - [Tour of the Dashboard](/dashboard-guides.md): What each view does: apps, users, monitoring, your team, billing and modules. --- title: "Dashboard Quickstart" description: "Sign in to the Block-Auth Dashboard with your identity, no passwords." url: "/dashboard-quickstart/" language: "en" --- # Quickstart Sign in to the Dashboard with your Block-Auth identity. No passwords and no forms: it takes a minute. [Go to Dashboard](https://dashboard.block-auth.io) --- ## Sign Up All you need is your Block-Auth identity, created with the browser extension or the mobile app. If you don't have one yet, follow the [Browser Extension Quickstart](/extension-quickstart.md) first. ### 1. Sign in with Block-Auth Open the Dashboard and press the Block-Auth button. _Screenshot: Dashboard sign-in screen_ ### 2. Approve the request Your extension (or the mobile app) opens. Accept the privacy policy and the terms and press **Accept**. _Screenshot: Sign-in request in the extension_ ### 3. Done You're in. Next, register your first application: press **Go to Applications** and follow the [Integration Quickstart](/integration-quickstart.md#applications). _Screenshot: Dashboard Overview_ --- title: "Block-Auth Dashboard Guides" description: "This section will guide you through the Block-Auth Dashboard and how to use it. We'll cover how to get started using the Block-Auth Dashboard." url: "/dashboard-guides/" language: "en" --- # Guides ## View: Applications In **Applications** you see every application you have created, with its basic information. Click an application to see its details. _Screenshot: Dashboard applications view_ ## View: Users management **Users management** has two tabs: **Users** and **Roles**. ### Users In **Users** you see every user who has signed in to your applications, their details and the roles assigned to them. _Screenshot: Dashboard users management view, users tab_ ### Roles In **Roles** you see the roles created for your applications, with their slug and description. _Screenshot: Dashboard users management view, roles tab_ ## View: Monitoring **Monitoring** opens **Logs and Activity**: the history of your applications' logins and transactions on the Block-Auth blockchain, with the details of each one. _Screenshot: Dashboard monitoring view_ ## View: Tenant settings Open **Settings** from the menu to reach **Tenant settings**. It has five tabs: **Settings**, **Invoices**, **Members**, **Roles** and **Permissions**. ### Settings In **Settings** you see and edit your tenant's details. _Screenshot: Dashboard tenant settings view_ ### Invoices In **Invoices** you see your tenant's invoices. ### Members In **Members** you see the people added to your tenant and their roles. _Screenshot: Dashboard tenant members view_ ### Roles In **Roles** you see the roles of your tenant's members. They are not the roles of your app's users, which are in **Users management**. _Screenshot: Dashboard tenant roles view_ ### Permissions In **Permissions** you see what each member role can do. _Screenshot: Dashboard tenant permissions view_ ## View: Add-ons In **Add-ons** you see the add-ons you can use in your applications, with their details, and you enable or disable them. Some are free and some are paid, per volume, per user or per request. _Screenshot: Dashboard modules view_ ### Enable an add-on Click **ENABLE** on the add-on. A window opens: if nothing else is needed, the add-on is enabled right away; otherwise, fill in the form it shows. _Screenshot: Module install modal_ _Screenshot: Module install modal confirming a successful installation_ _Screenshot: Installed module card with its scopes_ --- title: "Dashboard Roles" description: "Create tenant roles and assign them to users from the Block-Auth Dashboard." url: "/dashboard-roles/" language: "en" --- # Roles This guide shows how to create roles and assign them to users from the Dashboard. Once assigned, you can read those roles in your app with the [SDK Roles](/sdk-roles.md) guide. --- ## Prerequisites Before you begin, make sure you have: - A Block-Auth **company account** (tenant workspace). - At least one **linked and validated application**. If you have not completed this setup yet, follow the [Integration Quickstart](/integration-quickstart.md) first. --- ## 1. Create a role Open **Users management** in the sidebar and select the **Roles** tab. _Screenshot: Users management Roles tab_ Click **Add role**, enter a **name** and a **description**, then click **Create**. Spaces and symbols other than `-` and `_` are removed from the name. > **Note:** Block-Auth gives each role a slug, shown under its name in the list (for example acme-x7k2p9). Use that slug in your code, for example hasRoleBySlug('acme-x7k2p9'): unlike the name, it never changes. _Screenshot: Create role modal_ --- ## 2. Assign a role to a user Switch to the **Users** tab. Find the user you want to update and choose **Assign role** in the **Actions** column. _Screenshot: Users tab with assign role action_ In the modal, select the role you want to assign and click **Assign**. _Screenshot: Assign role modal_ The user will receive the assigned role on their next sign-in. To use roles in your application code, continue with [SDK Roles](/sdk-roles.md). --- --- title: "Integration Quickstart" description: "Set up Block-Auth before installing any SDK: your application, your keys, your development environment and your production domain." url: "/integration-quickstart/" language: "en" --- # Integration Quickstart Do these steps once, before installing any SDK. They are the same whether your app uses React, Vue, Angular, PHP, Python, .NET, Node.js or WordPress. Each application has two environments: **Development**, ready as soon as you create it so you can test on your computer, and **Production**, which turns on when you validate your domain. You can integrate and test everything locally and validate the domain only when you are about to go live. ## 1. Before you start You only need **one Block-Auth identity** and your Dashboard account: 1. **Create your identity** with the browser extension ([Chrome](https://chromewebstore.google.com/detail/block-auth-one/jhjjpmjhiamddbfhogknjibkacajkpdg), [Firefox](https://addons.mozilla.org/firefox/addon/block-auth-one/)) or the mobile app ([Google Play](https://play.google.com/store/apps/details?id=com.blockauthio.app)). See the [Browser Extension Quickstart](/extension-quickstart.md). 2. **Sign in to the Dashboard with that same identity.** See the [Dashboard Quickstart](/dashboard-quickstart.md). ## 2. Register your application Each website or app you connect to Block-Auth is an **application** in the Dashboard, with its own domain, keys and settings. In the sidebar, open **Applications** and press **Add** (or **Create your first application** if you don't have any yet). _Screenshot: Applications section with no applications_ In **Create your application**, fill in: - **Name**: the label you'll see for the app in the Dashboard. It can be anything. - **Domain**: the domain where your app will be published. You can paste the full address (for example `https://example.com/login`): the Dashboard keeps only the host, `example.com`. - **Product**: **Infinity** to authenticate your customers (B2C); **Nexus**, for your employees, is coming soon. Press **Create application**. _Screenshot: Create your application window_ Your application shows up in the list with its two environments side by side: - **Development** is already **Active on localhost**: you can start integrating. - **Production** shows **Validate your domain to start operating**: it turns on once you validate the domain ([step 5](#apps-validate-domain)). _Screenshot: Application card with its Production and Development environments_ ## 3. Get your keys Each environment has its own keys. Press **Integration details** on the environment you're going to use: **Development** while you code on your computer and **Production** on your live server. _Screenshot: Development environment application keys_ - The **API Key** (`apiKey`) is public: it can go in your frontend. - The **API Secret** (`apiSecret`) is private: keep it only in your server's environment variables, never in the browser or in your repository. The same window has a **Copy data for the guide** button. It copies your API Key and App URL, **without the secret**, so you can paste them later in the [SDK Quickstart](/sdk-integration.md#setup): with them, every code example in the guide comes out filled in for your app. ## 4. Develop on localhost The **Development** environment is created automatically with your application and needs no validated domain. Use it to test the login on your own computer: 1. Copy the **Development** keys into the `.env` on your computer. 2. Run your app on `http://localhost`, `http://127.0.0.1` or `http://[::1]`, on any port, and use that address as your `redirectUri`. 3. Follow your SDK guide ([step 7](#sdk-setup)) and sign in. How it works: - **Only your team can sign in to the development environment.** Block-Auth checks that the user belongs to the tenant that owns the app; anyone else gets `Local login is limited to the app team`. To let a colleague test, add them in **Settings → Members** ([Dashboard guides](/dashboard-guides.md)). - **The login screen shows a "Local development" notice** to whoever signs in. - **Your production app never accepts `localhost`**, only its validated domain. The development keys never open production. - **You can turn off either environment** with its **Allow sign-ins** switch, for example if a computer of your team is compromised. The other one keeps working. - **The development environment doesn't count** toward your plan's applications, users or transactions. - **Webhooks still need a public URL**: Block-Auth can't reach `localhost`. To receive them on your computer, expose your backend with a tunnel. ## 5. Validate your domain When you're about to publish your app, validate its domain to turn on **Production**. Press **Validate your domain to start operating** on your application's card. The **Validate your domain** window gives you a **TXT record** (type, name and value) to prove the domain is yours: 1. **Copy this TXT record.** 2. **Add it to your domain's DNS**, at your provider (Cloudflare, GoDaddy, OVH…). 3. **Verify the domain**: press **Verify domain** once you've saved it. _Screenshot: Validate your domain window with the TXT record_ After you save the record, DNS usually takes 1 to 5 minutes to propagate (sometimes up to 1 hour and, in rare cases, up to 24 hours). If verification fails, wait a few minutes and press **Verify domain** again. Once verified, **Production** becomes **Active** and its keys start working on your domain. _Screenshot: Application card with Production active_ Important matching rule Use the same host in DNS as the one you entered in the app's Domain field. Set TXT Name to that host: If your domain is a root domain (for example example.com), Cloudflare may show it as @ or example.com (both are equivalent). If your domain is a subdomain (for example app.example.com), use that subdomain host (for example app or app.example.com, depending on your DNS UI). Set TXT Content to the exact value shown by Block-Auth (no changes). ### Cloudflare example Open your domain's Cloudflare dashboard, go to **DNS** in the left sidebar and select **Records**. _Screenshot: Cloudflare DNS records navigation_ Press **Add record** to add your TXT record. _Screenshot: Cloudflare add DNS record form_ Create the record like this: - Choose `TXT` as the record type. - In `Name`, enter your domain as in the example below. - In `Content`, paste the value exactly as you copied it from the dashboard. _Screenshot: Cloudflare TXT record values example_ Press **Save** and go back to the dashboard to press **Verify domain**. **If you use another DNS provider, create the equivalent TXT record there.** ## 6. Set the webhook URL (optional) Block-Auth can notify your server when a user signs out of your app from Block-Auth or unlinks it, so you can close their session too. In the Dashboard, open your application and go to **Authentication**. The third URL field, shown as **"When user fails to log in"**, is where Block-Auth sends these notifications. Your domain is already filled in: type only the path, for example `/auth/blockauth/webhook`. The SDK guide you pick next tells you which path to use and how to verify the request. _Screenshot: Authentication block with the URL redirects_ ## 7. Set up your app in the guide Your application is ready. Open the [SDK Quickstart](/sdk-integration.md#setup) and fill in the form with your app data: it takes you to the guide for your app, already filled in with your data. --- title: "SDK Quickstart" description: "Pick the guide for your app and integrate Block-Auth from zero to production: React, Vue or Angular; PHP, Python, .NET or Node.js; or WordPress." url: "/sdk-integration/" language: "en" --- # SDK Quickstart Each guide takes you from zero to production, step by step. Pick the one that matches your app and follow only that one. Do its Quickstart steps, then Go live. ## How the pieces connect Pick your stack and hover over a piece or a step to follow it. The two login flows, step by step. On the website this is an interactive diagram. **React, Vue, Angular (+ backend), widget in a popup:** 1. Your frontend → Block-Auth: Login in a popup (PKCE) 2. Block-Auth → Your frontend: One-time code 3. Your frontend → Your backend: `POST /code` 4. Your backend → Block-Auth: `POST /api/auth/token` 5. Block-Auth → Your backend: `{ address, roles }` 6. Your backend → Your frontend: httpOnly session cookie 7. Your frontend → Your backend: `GET /me` 8. Your backend → Your frontend: `{ address, roles }` **PHP, Python, .NET, Node.js, and WordPress (redirect login):** 1. Your pages → Your backend: `GET /blockauth/login` 2. Your backend → Block-Auth: `POST /api/auth/authorize` 3. Your backend → Your pages: Redirect to the login 4. Your pages → Block-Auth: The user signs in 5. Block-Auth → Your pages: Back with ?code\&state 6. Your pages → Your backend: `GET /blockauth/callback` 7. Your backend → Block-Auth: `POST /api/auth/token` 8. Block-Auth → Your backend: `{ address, roles }` 9. Your backend → Your pages: Session cookie and redirect ## Why your backend redeems the code Never let your backend trust a user `address` sent by the browser. The browser decides what it sends, and whether an address is signed into your app is public on-chain data: anyone could send another user's address and get their session. That is why every guide ends the same way: Block-Auth gives the browser a **one-time code**, useless without your `apiSecret`, and **your backend** redeems it at `POST /api/auth/token` to get the user's address and roles from Block-Auth itself. Only then does it create its own session. The only exception is [frontend only](/sdk-integration-frontend.md), for apps without a backend: the widget signs the user in by itself, so it only shows who is signed in and no server can trust that session. ## Set up your integration Pick your guide and fill it in once. With this data and these choices, every code example and file in the guide comes out adapted to your app, ready to copy. What can’t be filled in for security, like the API Secret, is marked with a note next to the code. On the website this is a form that fills every example with the app’s data. In the Markdown versions the examples keep placeholders such as `your_api_key` and `https://your-app.com`: replace them with the app’s values, following the [placeholders table](/sdk-integration-checklist.md#placeholders). --- title: "Roles" description: "Give your users roles in the Dashboard and use them in your app: show or hide UI in the frontend and protect routes in your backend." url: "/sdk-roles/" language: "en" --- # Roles Give your users roles in the Dashboard, such as `admin` or `editor`, and use them in your app. Block-Auth sends the user's roles with every login. ## Create and assign roles In the Dashboard, create the roles and assign them to your users. See [Dashboard roles](/dashboard-roles.md). Each role has a **name**, which you choose and can rename, and a **slug**, which Block-Auth generates when you create the role (for example `acme-x7k2p9`) and never changes. Use the slug in your code: copy it from the **Roles** tab in the Dashboard, under the role's name. ## Show or hide UI Once the user has logged in with the widget, read their roles in the frontend. They come from your backend's answer (`/code` and `/me` in the [backend routes](/sdk-integration-spa-backend.md#backend-routes)), so you don't need anything else. **React** ```jsx import { useBlockAuthUser } from '@block-auth.io/react' export function AdminLink() { const { hasRoleBySlug, isLoadingUser } = useBlockAuthUser() if (isLoadingUser || !hasRoleBySlug('acme-x7k2p9')) return null return Admin panel } ``` **Vue** ```vue ``` **Angular** ```typescript import { Component, inject } from '@angular/core' import { BlockAuthService } from '@block-auth.io/angular' @Component({ selector: 'app-admin-link', standalone: true, template: ` @if (!auth.isLoadingUser() && auth.hasRoleBySlug('acme-x7k2p9')) { Admin panel } `, }) export class AdminLinkComponent { auth = inject(BlockAuthService) } ``` > **Placeholders in this code:** > > - Replace `acme-x7k2p9` with the slug of one of your roles: copy it from the Roles tab in the Dashboard, under the role name. **Only for Angular:** **Angular with `templateUrl`:** the examples put the HTML inside `template`. If your component has its HTML in its own file (`templateUrl`, the default in new Angular projects, like `app.ts` and `app.html`), move what's inside `template` to that `.html` file and keep the rest (`imports` and the methods) in the `.ts` file. > **Note:** Hiding a button is not security: anyone can call your backend directly. Check the role in your backend too. ## Protect your backend > How you add the backend login routes: this page covers “With the Block-Auth package” or “My own implementation”. Both variants are written out below, each one marked. Follow only the one that matches the app. ### How you add the backend login routes: With the Block-Auth package. Your backend gets the roles when it redeems the login code (`/api/auth/token`) and keeps them in the user's session. Check them there before doing anything that needs a role. With the [Block-Auth package](/sdk-integration-spa-session.md#protect-routes), read the user with `currentUser`, which also ends the session at `signedExpiredAt` (in .NET the roles are role claims): **Node.js** ```js import { expressSessionStore } from '@block-auth.io/node/express' function requireRole(slug) { return async (req, res, next) => { const user = await routes.currentUser({ session: expressSessionStore(req) }) if (!user?.roles.some((role) => role.slug === slug)) { return res.status(403).json({ error: 'Forbidden' }) } next() } } app.get('/api/admin/stats', requireRole('acme-x7k2p9'), getStats) ``` **PHP** ```php function requireRole(BlockAuthRoutes $routes, string $slug): void { $roles = $routes->currentUser()['roles'] ?? []; if (!in_array($slug, array_column($roles, 'slug'), true)) { http_response_code(403); exit; } } requireRole($routes, 'acme-x7k2p9'); ``` **Python** ```python from functools import wraps from flask import abort from blockauth_sdk.routes.flask import session_store def require_role(slug): def decorator(view): @wraps(view) def wrapped(*args, **kwargs): roles = (routes.current_user(session_store()) or {}).get("roles", []) if not any(role["slug"] == slug for role in roles): abort(403) return view(*args, **kwargs) return wrapped return decorator @app.get("/api/admin/stats") @require_role("acme-x7k2p9") def admin_stats(): return get_stats() ``` **.NET** ```csharp app.MapGet("/api/admin/stats", () => GetStats()) .RequireAuthorization(policy => policy.AddAuthenticationSchemes("BlockAuth").RequireRole("acme-x7k2p9")); ``` > **Placeholders in this code:** > > - Replace `acme-x7k2p9` with the slug of one of your roles: copy it from the Roles tab in the Dashboard, under the role name. ### How you add the backend login routes: My own implementation. Your backend gets the roles when it redeems the login code (`/api/auth/token`) and keeps them in the user's session. Check them there before doing anything that needs a role. `currentUser` (`current_user` in Python, `CurrentAddress` in .NET) is the helper from your guide's login routes, which also ends the session at `signedExpiredAt`: **Node.js** ```js function requireRole(slug) { return (req, res, next) => { const roles = currentUser(req)?.roles ?? [] if (!roles.some((role) => role.slug === slug)) { return res.status(403).json({ error: 'Forbidden' }) } next() } } app.get('/api/admin/stats', requireRole('acme-x7k2p9'), getStats) ``` **PHP** ```php function requireRole(string $slug): void { $roles = currentUser()['roles'] ?? []; if (!in_array($slug, array_column($roles, 'slug'), true)) { http_response_code(403); exit; } } requireRole('acme-x7k2p9'); ``` **Python** ```python from functools import wraps from flask import abort, session def require_role(slug): def decorator(view): @wraps(view) def wrapped(*args, **kwargs): roles = (current_user() or {}).get("roles", []) if not any(role["slug"] == slug for role in roles): abort(403) return view(*args, **kwargs) return wrapped return decorator @app.get("/api/admin/stats") @require_role("acme-x7k2p9") def admin_stats(): return get_stats() ``` **.NET** ```csharp bool HasRole(HttpContext http, string slug) { if (CurrentAddress(http) is null) return false; using var roles = JsonDocument.Parse(http.Session.GetString("roles") ?? "[]"); return roles.RootElement.EnumerateArray() .Any(role => role.GetProperty("slug").GetString() == slug); } app.MapGet("/api/admin/stats", (HttpContext http) => HasRole(http, "acme-x7k2p9") ? Results.Ok(GetStats()) : Results.StatusCode(403)); ``` > **Placeholders in this code:** > > - Replace `acme-x7k2p9` with the slug of one of your roles: copy it from the Roles tab in the Dashboard, under the role name. Roles are read at login. If you change a user's roles in the Dashboard, your backend sees them on the user's next login. ## Reference `useBlockAuthUser()` in React and Vue, and the `BlockAuthService` signals in Angular, return: | Value | What it is | | ------------------------------------- | -------------------------------------------------------------- | | `roles` | The user's roles, as `{ name, slug }`. | | `roleNames` / `roleSlugs` | Only the names, or only the slugs. | | `hasRoleBySlug(slug)` | `true` if the user has that role. | | `hasAnyRoleBySlug(slugs)` | `true` if the user has at least one of them. | | `hasRole(name)` / `hasAnyRole(names)` | The same, by name. Not case-sensitive. | | `isLoadingUser` | `true` while the user is loading. Wait for it before deciding. | | `user` | The logged-in user (`address`, `did`, `roles`), or `null`. | --- title: "Integration checklist" description: "What to go over before calling your Block-Auth integration done: the security rules, the placeholders to replace and how to check that it works." url: "/sdk-integration-checklist/" language: "en" --- # Integration checklist Go over it before calling your integration done, whichever guide you follow: the security rules it must keep, the example values to replace and how to check that it works. ## Security rules Your integration must keep all these rules. Each one is explained in the guides and in [Security](/security.md). - **The API Secret only lives in the backend.** Read it from an environment variable or your secret store. Never put it in frontend code, in a `VITE_`, `NEXT_PUBLIC_` or `REACT_APP_` variable, in Angular's `environment.ts`, in a committed file or in a log. The API Key is public and goes in the frontend. - **The browser never decides who the user is.** The widget only hands a one-time code to the backend. The backend redeems it at `POST /api/auth/token` with the API Secret (the Block-Auth packages do it for you) and only then creates its own session. Never trust a user or address sent by the browser. - **With the Node.js package, the order matters.** Mount `blockauthRouter(routes)` after `session(...)` and before `express.json()`, and make the session cover `/auth/blockauth`, not only `/api`. - **The widget calls `/auth/blockauth` on the same origin as the page.** In development, use your dev server's proxy. In production, serve the frontend from the backend or send `/auth/blockauth` to it with a reverse proxy, over `https`. Don't open CORS for it. - **With the redirect login, check `state`** before redeeming the code. - **Verify every webhook** before trusting it: the Block-Auth packages do it, and the [Webhooks](/webhooks.md) page explains how to do it yourself. - **Use role slugs, not names.** Role names can change; slugs never do. - **Don't let the session outlive `signedExpiredAt`**, the moment the user's signature for the app expires ([how long a session lasts](/security.md#session)). - **Frontend only (`authEndpoint: false`) only shows who is signed in.** There's no backend redeeming the code, so the rules about the backend and `/auth/blockauth` don't apply to it, but no server has a session it can trust either. Never use the address the page knows to authorize anything on a server: if the app has an API or private data, follow [React, Vue or Angular (+ backend)](/sdk-integration-spa.md). ## Placeholders The code in the docs uses these placeholders. Replace every one before finishing, and never with a made-up value: | Placeholder | What to do | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `sha256_hex_of_your_api_secret`, `sha256_of_api_secret` | Replace the `sha256_…` value with the SHA-256 hash (hex) of your API Secret. Compute it on your computer, never on a web page. | | `your_api_secret`, ``, `` | Replace the API Secret placeholder with your API Secret, copied straight from the Dashboard. Never paste it on this site. | | `a_long_random_string`, ``, `` | Replace the SESSION\_SECRET placeholder with a random value generated on your computer: `openssl rand -hex 32`. | | `your_api_key` | Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you. | | `https://your-app.com` | Replace `https://your-app.com` with your app URL, or fill in your data in the SDK Quickstart and it is filled in for you. | | `your-app.com` | Replace `your-app.com` with your domain, or fill in your data in the SDK Quickstart and it is filled in for you. | | `https://example.com` | Replace `https://example.com` with your app’s validated domain. | | `https://your-site.com` | Replace `https://your-site.com` with your WordPress site URL. | | `acme-x7k2p9` | Replace `acme-x7k2p9` with the slug of one of your roles: copy it from the Roles tab in the Dashboard, under the role name. | | `"your-app": {` | Replace `your-app` with your project name: the key you already have under `projects` in your `angular.json`. | | `your_access_token` | Replace `your_access_token` with the access token you get from `/api/signin`. It lasts 1 hour. | | `your_refresh_token` | Replace `your_refresh_token` with the refresh token you got from `/api/signin`. | | `code_from_the_widget`, `code_verifier_from_the_widget`, `redirect_uri_from_the_widget` | Replace the `…_from_the_widget` values with the ones the widget sends to your `/code` route. | | `code_from_your_callback` | Replace `code_from_your_callback` with the `code` Block-Auth sends to your callback URL. | | `"your-app"` | Replace `your-app` with your project name in `angular.json`. | | `findUser`, `saveSignout`, `lastSignout`, `removeLink`, `endSessionsOf`, `markUnlinked`, `alreadyProcessed`, `isLinked`, `saveLink`, `listOrders`, `deleteOrder` | `findUser`, `saveSignout`… are yours: replace them with your app’s own functions (your database, your cache…). | ## Definition of done The integration is done when the last Quickstart step, Go live, passes on your domain. Before that, the same check must pass in development: - **React, Vue or Angular:** after signing in with the Block-Auth button, `GET /auth/blockauth/me` in the same browser returns the user. A `404` or your app's page means the request doesn't reach the backend; a `401` means the login didn't create the session. See [Connect and try it](/sdk-integration-spa-connect.md#try-it). - **React, Vue or Angular, frontend only:** after signing in with the Block-Auth button, it turns into the profile menu, and the user is still signed in after reloading the page. See [Try it](/sdk-integration-frontend-try.md). - **PHP, Python, .NET, Node.js:** opening `/blockauth/login` and signing in brings the user back signed in, and `GET /api/me` returns them. See [Login](/sdk-integration-server-login.md#try-it). - **WordPress:** after signing out, the Block-Auth button on `/wp-login.php` signs the user in to WordPress. See [Connect it](/sdk-integration-wordpress-connect.md#try-it). Also check that the API Secret doesn't appear anywhere in the frontend build output or in the repository, and that the app's own lint and tests still pass. ## For AI assistants If an AI assistant (Claude Code, Cursor, Copilot, ChatGPT…) does the integration, give it the docs in Markdown. The website shows one framework, backend or environment at a time; the Markdown has every variant at once: - [`/llms.txt`](/llms.txt): the index of every page, with the guides in order. - [`/llms-full.txt`](/llms-full.txt): every page in a single file. - `/llms/.md`: one guide per stack (for example [`/llms/react-vite-node.md`](/llms/react-vite-node.md)), with only its steps, in order. The list is in `/llms.txt`. - Any page with `.md` added to its path, for example [`/sdk-integration-spa-backend.md`](/sdk-integration-spa-backend.md). Each page also points to it with ``. In the Markdown versions every tab and option is written out and marked (for example, _Only for Node.js_ or _In production_), and the code keeps its placeholders. Follow only the variant that matches the app. ### Pick your guide Look at the app first, then follow one guide only, from its first page to the end of its Quickstart: | If the app… | Follow | | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | Has a React, Vue or Angular frontend (Vite, Next.js, Create React App or Angular CLI) and a backend in any language | [React, Vue or Angular (+ backend)](/sdk-integration-spa.md) | | Has a React, Vue or Angular frontend and no backend, and only needs to show who is signed in | [React, Vue or Angular (frontend only)](/sdk-integration-frontend.md) | | Renders its pages on the server, in PHP, Python, .NET or Node.js, without a React, Vue or Angular frontend | [PHP, Python, .NET, Node.js](/sdk-integration-server.md) | | Is a WordPress site | [WordPress](/sdk-integration-wordpress.md) | Every guide except frontend only needs a backend that redeems the login code (in WordPress, the plugin is that backend). Before the first step, the app must exist in the [Dashboard](/integration-quickstart.md#applications) with its keys: if an AI assistant does the integration, give it the API Key yourself and set the API Secret yourself. ### Required steps Each guide starts with a page to read first and then the Quickstart steps, in this order. All of them are required. The pages under **More options** (webhooks, linking users, customizing the widget) are optional: add them when the app needs them. **React, Vue, Angular (+ backend)** 1. [Before you start](/sdk-integration-spa.md) 2. [Your frontend](/sdk-integration-spa-frontend.md): Install the widget and add the login button. 3. [Your backend](/sdk-integration-spa-backend.md): Add the routes that redeem the login code. 4. [Connect and try it](/sdk-integration-spa-connect.md): Connect your frontend to your backend and check the login. 5. [Go live](/sdk-integration-spa-go-live.md) **React, Vue, Angular (frontend only)** 1. [Before you start](/sdk-integration-frontend.md) 2. [Your frontend](/sdk-integration-frontend-setup.md): Install the widget and add the login button. 3. [Try it](/sdk-integration-frontend-try.md): Sign in, reload and sign out. 4. [Go live](/sdk-integration-frontend-go-live.md) **PHP, Python, .NET, Node.js** 1. [Before you start](/sdk-integration-server.md) 2. [Install the client](/sdk-integration-server-install.md): Set up your environment variables and install the Block-Auth client for your language. 3. [Login](/sdk-integration-server-login.md): Add the login routes, link your pages and try it. 4. [Go live](/sdk-integration-server-go-live.md) **WordPress** 1. [Before you start](/sdk-integration-wordpress.md) 2. [Install the plugin](/sdk-integration-wordpress-install.md): Upload and activate the Block-Auth Login plugin. 3. [Connect it](/sdk-integration-wordpress-connect.md): Connect your keys, choose the login and try it. 4. [Go live](/sdk-integration-wordpress-go-live.md) ### Working with the developer Before writing code, find out or ask: - The stack: frontend framework and build tool, backend language and framework, whether frontend and backend share one project. - Whether the app already has its own login, and where its session and its "who am I" route live. - The port the backend already listens on, and the URL where the frontend opens (the App URL). - Whether the app already exists in the Block-Auth Dashboard, and its API Key (public). Development and production have different keys. Never ask for the API Secret or the `SESSION_SECRET` in the conversation, and never write them into code or commit them. Tell the developer which environment variable to set and how to generate `SESSION_SECRET` (`openssl rand -hex 32`), and check that `.env` is in `.gitignore`. While implementing: - Read the existing server first: where the app is created, its session, its body parsers, how it loads variables and how its tests build it. Add the Block-Auth lines into that structure instead of replacing it with the examples' full server. - Keep every Block-Auth value in the app's existing configuration (for example its config module), not scattered `process.env` reads. - Keep the app's lint and tests passing; give the tests test values, never real keys. When you finish, tell the developer: the files you changed, the variables they must set and where, the exact steps to try it (the definition of done above) and the optional next steps (webhooks, using the session in their routes, going live). If something fails, ask for the exact error line from the browser console and the backend console, with a `logger` passed to `BlockAuthRoutes`, and match it in [Troubleshooting](/troubleshooting.md). --- title: "Integration with React, Vue or Angular" description: "Add Block-Auth to a React, Vue or Angular app: the login widget in your frontend and three routes in your backend." url: "/sdk-integration-spa/" language: "en" guide: "React, Vue, Angular (+ backend)" step: "Read first" --- # React, Vue or Angular Follow this guide if your frontend is a React, Vue or Angular app. At the end your users sign in with Block-Auth and your backend has a verified session for them. ## What you'll build You need **two pieces**, and this guide covers both: - **In your frontend:** the Block-Auth widget (`@block-auth.io/react`, `/vue` or `/angular`). It shows the sign-in button and opens the login. - **In your backend:** three routes that redeem the login code with your API secret. Your backend can be in any language: the examples are in Node.js, PHP, Python and .NET. The browser never decides who the user is: the widget only passes a one-time code to your backend, and your backend gets the user from Block-Auth. 1. Your frontend → Block-Auth: Login in a popup (PKCE) 2. Block-Auth → Your frontend: One-time code 3. Your frontend → Your backend: `POST /code` 4. Your backend → Block-Auth: `POST /api/auth/token` 5. Block-Auth → Your backend: `{ address, roles }` 6. Your backend → Your frontend: httpOnly session cookie 7. Your frontend → Your backend: `GET /me` 8. Your backend → Your frontend: `{ address, roles }` ## Prepare your app 1. In the Dashboard, create your application following the [Integration Quickstart](/integration-quickstart.md#applications). As the domain, enter the host where your **frontend** runs (for example `your-app.com`). 2. Pick the keys based on where your app is going to run. Each environment has its own in [Applications » Integration details](/integration-quickstart.md#apps-retrieve-keys), and they don't mix: | Where your app runs | Which keys to use | Where you put them | | --------------------------- | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | Your computer (`localhost`) | The **Development** ones. They work right away. | The `.env` on your computer | | Your live server | The **Production** ones. They work once you [validate your domain](/integration-quickstart.md#apps-validate-domain). | Your server's environment variables | 3. Fill in your data once in the [SDK Quickstart](/sdk-integration.md#setup): from then on, each guide gives you the files and code already adapted to your app. Next: [Your frontend](/sdk-integration-spa-frontend.md), the first required step. --- title: "React, Vue or Angular: your frontend" description: "Install and set up the Block-Auth widget in your React, Vue or Angular app." url: "/sdk-integration-spa-frontend/" language: "en" guide: "React, Vue, Angular (+ backend)" step: "Quickstart step 1 of 4, required" --- # Your frontend Install and set up the Block-Auth widget in your React, Vue or Angular app. ## Your environment variables Before you touch any code, create the `.env` files for your frontend and your backend. Your `apiKey` is public and goes in the frontend; your `apiSecret` goes only in the backend. Here they are with your data: #### Vite (React · Vue) · development This is your frontend’s `.env`. The backend has its own file. **.env, next to the frontend package.json** ```dotenv VITE_BLOCKAUTH_API_KEY=your_api_key ``` #### Vite (React · Vue) · production It’s baked into the build, so it must exist where you build for production. Pick how you build: **File · .env.production · in your frontend folder** ```dotenv VITE_BLOCKAUTH_API_KEY=your_api_key ``` **Docker · Dockerfile · right before npm run build** ```dotenv ARG VITE_BLOCKAUTH_API_KEY RUN npm run build ``` **Docker · docker-compose.yml · in the service that builds your frontend** ```dotenv build: args: VITE_BLOCKAUTH_API_KEY: ${BLOCKAUTH_API_KEY} ``` **CI · Variable of your CI · in the job that runs npm run build** ```dotenv VITE_BLOCKAUTH_API_KEY=your_api_key ``` #### Next.js (React) · development This is your frontend’s `.env.local`. The backend has its own file. **.env.local, at the project root** ```dotenv NEXT_PUBLIC_BLOCKAUTH_API_KEY=your_api_key ``` #### Next.js (React) · production It’s baked into the build, so it must exist where you build for production. Pick how you build: **File · .env.production · in your frontend folder** ```dotenv NEXT_PUBLIC_BLOCKAUTH_API_KEY=your_api_key ``` **Docker · Dockerfile · right before npm run build** ```dotenv ARG NEXT_PUBLIC_BLOCKAUTH_API_KEY RUN npm run build ``` **Docker · docker-compose.yml · in the service that builds your frontend** ```dotenv build: args: NEXT_PUBLIC_BLOCKAUTH_API_KEY: ${BLOCKAUTH_API_KEY} ``` **CI · Variable of your CI · in the job that runs npm run build** ```dotenv NEXT_PUBLIC_BLOCKAUTH_API_KEY=your_api_key ``` #### Create React App (React) · development This is your frontend’s `.env`. The backend has its own file. **.env, at the project root** ```dotenv REACT_APP_BLOCKAUTH_API_KEY=your_api_key ``` #### Create React App (React) · production It’s baked into the build, so it must exist where you build for production. Pick how you build: **File · .env.production · in your frontend folder** ```dotenv REACT_APP_BLOCKAUTH_API_KEY=your_api_key ``` **Docker · Dockerfile · right before npm run build** ```dotenv ARG REACT_APP_BLOCKAUTH_API_KEY RUN npm run build ``` **Docker · docker-compose.yml · in the service that builds your frontend** ```dotenv build: args: REACT_APP_BLOCKAUTH_API_KEY: ${BLOCKAUTH_API_KEY} ``` **CI · Variable of your CI · in the job that runs npm run build** ```dotenv REACT_APP_BLOCKAUTH_API_KEY=your_api_key ``` #### Angular (environment.ts) · development Angular doesn’t use .env: your apiKey goes in this file. The backend variables go in their own file, your backend’s `.env`. **src/environments/environment.ts** ```typescript export const environment = { blockauthApiKey: 'your_api_key', } ``` #### Angular (environment.ts) · production Keep `environment.ts` with the development key and put the production one in `environment.prod.ts`, next to it. Then tell `angular.json` to swap them in the production build (`ng build`, the default configuration), so development keeps working on `localhost`. **src/environments/environment.prod.ts · new file** ```typescript export const environment = { blockauthApiKey: 'your_api_key', } ``` **angular.json · inside projects › your-app › architect › build › configurations › production** ```dotenv "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ] ``` #### apiKey written in the widget config (React · Vue · Angular) · development and production Your apiKey goes straight into the widget config (next step), no environment file. In the widget config, read the apiKey from that variable instead of writing `your_api_key`: - Vite (`src/main.jsx · src/main.ts`): `apiKey: import.meta.env.VITE_BLOCKAUTH_API_KEY,` - Next.js (`app/layout.tsx`): `apiKey: process.env.NEXT_PUBLIC_BLOCKAUTH_API_KEY,` - Create React App (`src/index.js`): `apiKey: process.env.REACT_APP_BLOCKAUTH_API_KEY,` - Angular (`src/app/app.config.ts`): `apiKey: environment.blockauthApiKey,` > **Placeholders in this code:** > > - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you. `APP_URL` in development is the URL where your frontend runs: Vite `http://localhost:5173`, Next.js `http://localhost:3000`, Create React App `http://localhost:3000`, Angular `http://localhost:4200`. #### Node.js · development In a .env next to your backend package.json. Load it with `node --env-file=.env` (Node 20.6+) or the `dotenv` package (`import 'dotenv/config'` at the top of your entry file). **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Node.js · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### PHP · development getenv() doesn't read .env files by itself: set them in your server (`SetEnv` in Apache, `env[]` in PHP-FPM), or load the .env with `vlucas/phpdotenv`. **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= ``` #### PHP · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= ``` #### Python (Flask) · development In a .env in your backend folder. `flask run` loads it if `python-dotenv` is installed; with `python app.py`, gunicorn or waitress, call `load_dotenv()` first, use `uv run --env-file .env …` or export the variables. **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Python (Flask) · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Python (FastAPI) · development In a .env in your backend folder. Start uvicorn with `--env-file .env` (needs `python-dotenv` installed) or, with uv, `uv run --env-file .env uvicorn …`, or export the variables. **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Python (FastAPI) · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### .NET · development The public values go in `appsettings.json`. The secret never goes in a file you commit: in development use `user-secrets`, in production an environment variable. **appsettings.json** ```json { "APP_URL": "http://localhost:5173", "BLOCKAUTH_API_KEY": "your_api_key" } ``` **Terminal, in the project folder (development only)** ```bash dotnet user-secrets init dotnet user-secrets set "BLOCKAUTH_API_SECRET" "" ``` #### .NET · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **appsettings.json** ```json { "APP_URL": "https://your-app.com", "BLOCKAUTH_API_KEY": "your_api_key" } ``` **Environment variable on your server (never in a repo file)** ```dotenv BLOCKAUTH_API_SECRET= ``` > **Placeholders in this code:** > > - Replace the API Secret placeholder with your API Secret, copied straight from the Dashboard. Never paste it on this site. > - Replace the SESSION\_SECRET placeholder with a random value generated on your computer: `openssl rand -hex 32`. > - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you. > - Replace `https://your-app.com` with your app URL, or fill in your data in the SDK Quickstart and it is filled in for you. ## Install the widget Run it in your **frontend** folder, the one that already has the `package.json` of your React, Vue or Angular app. If your frontend is in a subfolder, like `frontend/` or `client/`, go into it first. If frontend and backend share one `package.json`, it's the project root: **React · Terminal · in your frontend package.json folder** ```bash npm install @block-auth.io/react ``` **Vue · Terminal · in your frontend package.json folder** ```bash npm install @block-auth.io/vue ``` **Angular · Terminal · in your frontend package.json folder** ```bash npm install @block-auth.io/angular ``` Check that the package shows up in that `package.json`. If npm created a new `package.json`, you were in another folder: delete it along with its `node_modules` and run the install again in your frontend folder. **Angular:** the widget brings wallet libraries with CommonJS modules and optional dependencies the Angular builder can't resolve. Add them to the build options in `angular.json`, or the build warns and fails. Also raise the `initial` budget of the production build: the wallets add about 1 MB and the default limit of new Angular projects (1 MB) stops `ng build`. If your `angular.json` already has `budgets`, change only the `initial` one. Select the **Angular** tab to see the configuration. **Only for Angular:** **angular.json · At the root of your Angular project** ```json { "projects": { "your-app": { "architect": { "build": { "options": { "allowedCommonJsDependencies": ["crypto-js", "qrcode", "bs58", "socket.io-client"], "externalDependencies": [ "@base-org/account", "@coinbase/wallet-sdk", "@metamask/connect-evm", "porto", "porto/internal", "@safe-global/safe-apps-provider", "@safe-global/safe-apps-sdk", "@walletconnect/ethereum-provider" ] }, "configurations": { "production": { "budgets": [ { "type": "initial", "maximumWarning": "2MB", "maximumError": "3MB" } ] } } } } } } } ``` > **Placeholders in this code:** > > - Replace `your-app` with your project name: the key you already have under `projects` in your `angular.json`. ## Configure the widget Add it once, in the file where your app starts: `src/main.jsx` in React with Vite (`src/index.js` with CRA), `src/main.ts` (or `src/main.js`) in Vue and `app.config.ts` in Angular. Your app doesn't change: in React you wrap it as is, with everything it already has inside, and in Vue you add the `.use()` to the chain you already have (for example, next to `.use(router)`), before `.mount()`. **For every setup except React + Next.js:** **React · src/main.jsx · where your app starts** ```jsx import { createRoot } from 'react-dom/client' import { BlockAuthProvider } from '@block-auth.io/react' import { App } from './App' const config = { apiKey: 'your_api_key', locale: 'en', } createRoot(document.getElementById('root')).render( , ) ``` **Vue · src/main.ts (or main.js) · where your app starts** ```typescript import { createApp } from 'vue' import { createBlockAuth } from '@block-auth.io/vue' import App from './App.vue' createApp(App) .use( createBlockAuth({ apiKey: 'your_api_key', locale: 'en', }), ) .mount('#app') ``` **Angular · src/app/app.config.ts** ```typescript import { ApplicationConfig } from '@angular/core' import { provideBlockAuth } from '@block-auth.io/angular' export const appConfig: ApplicationConfig = { providers: [ provideBlockAuth({ apiKey: 'your_api_key', locale: 'en', }), ], } ``` > **Placeholders in this code:** > > - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you. **Only for React + Next.js:** In Next.js (App Router), the provider goes in a Client Component. Create `app/providers.jsx` and use it in your root `layout`, wrapping `children`. Tested with Next.js 16; with webpack instead of Turbopack (Next.js 15, or `next build --webpack`) the build fails today, so use Turbopack. **React · app/providers.jsx · new file** ```jsx 'use client' import { BlockAuthProvider } from '@block-auth.io/react' const config = { apiKey: 'your_api_key', locale: 'en', } export function Providers({ children }) { return {children} } ``` > **Placeholders in this code:** > > - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you. **React · app/layout.jsx · your root layout** ```jsx import { Providers } from './providers' export default function RootLayout({ children }) { return ( {children} ) } ``` Any component that uses `FlowBlockAuth` or the hooks also starts with `'use client'`. **Only for React + Create React App:** **CRA:** the build warns `Can't resolve '@walletconnect/ethereum-provider'`, an optional dependency the widget doesn't use. You can ignore it; with `CI=true`, CRA turns warnings into errors, so build with `CI=false`. > **Note:** Never put the `apiSecret` in your frontend, not even in an environment > variable like `VITE_…` or `NEXT_PUBLIC_…`: the bundler copies it into the > JavaScript every visitor downloads. The widget doesn't need it: if you pass > it, the SDK sends it from the browser. ### Config options - `apiKey` _(string, required)_: your app's API key. It's public: it only says which app is calling. - `authEndpoint` _(string | false)_: base path of your [backend routes](/sdk-integration-spa-backend.md#backend-routes). By default `/auth/blockauth`: set it only if your routes live under another path, and set the same path as `basePath` in your backend package. To turn off a package route you don’t use, pass `routes: { link: false }` (in .NET, `DisabledRoutes`). Serve it from the same origin as your frontend, so the session cookie travels with every request. If a route is missing or doesn't answer, the browser console says what to fix. Set it to `false` only if your app has no backend: the widget then signs the user in by itself, and your page knows their address but your server has no session it can trust. - `locale` _(string)_: language of the widget, `"en"` or `"es"`. By default, the browser's language. - `sessionCheckSeconds` _(number)_: how often the widget asks `/me` whether the session is still open, besides every time the tab gets focus. By default `60`; `0` turns it off. - `onSessionEnded` _(function)_: called when your backend has closed the session, for example after the user signed out from Block-Auth Identity or the extension. The widget already shows the user as signed out: use it to leave private pages. - `wsUrl` _(string)_: the Block-Auth server the widget talks to. By default production (`wss://wss.block-auth.io`): change it only if Block-Auth gives you another environment to test against. The login itself happens on the Block-Auth login page (`auth.block-auth.io`), so you don't configure Google, Microsoft, wallets or WalletConnect in your app. > Your app today: this page covers “It already has a login” or “It has no login”. Both variants are written out below, each one marked. Follow only the one that matches the app. ## Add the login button ### Your app today: It already has a login. Put `FlowBlockAuth` on your login page, below your form, as another way in. **Don't replace your page:** add only the `FlowBlockAuth` import and the component right after your form (in Vue and Angular, also the `onSuccess` and `onError` functions). In the example, the `
` is your current form, which stays the same. After the login, reload the page: your app asks your backend again who the user is, and your backend resolves it with [your session or Block-Auth's](/sdk-integration-spa-session.md#protect-routes). **React · Example · your login page with the button added** ```jsx import { FlowBlockAuth } from '@block-auth.io/react' export function LoginPage() { return (
window.location.assign('/')} onError={() => alert('Sign-in failed, try again.')} />
) } ``` **Vue · Example · your login page with the button added** ```vue ``` **Angular · Example · your login page with the button added** ```typescript import { Component } from '@angular/core' import { FlowBlockAuthComponent } from '@block-auth.io/angular' @Component({ selector: 'app-login-page', imports: [FlowBlockAuthComponent], template: `
`, }) export class LoginPageComponent { onSuccess(): void { window.location.assign('/') } onError(): void { alert('Sign-in failed, try again.') } } ``` **Only for Angular:** **Angular with `templateUrl`:** the examples put the HTML inside `template`. If your component has its HTML in its own file (`templateUrl`, the default in new Angular projects, like `app.ts` and `app.html`), move what's inside `template` to that `.html` file and keep the rest (`imports` and the methods) in the `.ts` file. **When signing out**, also close the Block-Auth session: in the function where you already sign out, add a call to `POST /auth/blockauth/logout` with a JSON `{}` body. It works the same in React, Vue and Angular. In the example, `/api/logout` is your current logout, which stays the same: **Logout · Example · your logout function with the call added** ```javascript async function logout() { await fetch('/api/logout', { method: 'POST' }) await fetch('/auth/blockauth/logout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}', }) window.location.assign('/login') } ``` To let your current users reach their same account, [link them](/sdk-integration-spa-extras.md#link-users). ### Your app today: It has no login. Place `FlowBlockAuth` where you want the sign-in button. After the login it turns into the profile menu, and on reload it restores the session by asking your backend. **React · Your header · e.g. src/components/Header.jsx** ```jsx import { FlowBlockAuth } from '@block-auth.io/react' export function Header() { return (
console.log('Signed in as', address)} onError={() => alert('Sign-in failed, try again.')} onLogout={() => window.location.assign('/')} />
) } ``` **Vue · Your header · e.g. src/components/AppHeader.vue** ```vue ``` **Angular · Your header · e.g. src/app/header.component.ts** ```typescript import { Component } from '@angular/core' import { FlowBlockAuthComponent } from '@block-auth.io/angular' @Component({ selector: 'app-header', imports: [FlowBlockAuthComponent], template: `
`, }) export class HeaderComponent { onSuccess(address?: string): void { console.log('Signed in as', address) } onError(): void { alert('Sign-in failed, try again.') } onLogout(): void { window.location.assign('/') } } ``` **Only for Angular:** **Angular with `templateUrl`:** the examples put the HTML inside `template`. If your component has its HTML in its own file (`templateUrl`, the default in new Angular projects, like `app.ts` and `app.html`), move what's inside `template` to that `.html` file and keep the rest (`imports` and the methods) in the `.ts` file. If the browser blocks the popup, the widget opens the login in the same tab: Block-Auth sends the user back to the root of your app (`/`), which must load your frontend with the widget config, and the widget finishes the login on the page where it started. **Does your server send a `Content-Security-Policy`?** You won’t notice in development, but in production it blocks the widget: unstyled button, broken logo and failed login. When you deploy, allow it as explained in [Go live](/sdk-integration-spa-go-live.md#production-csp). ## Checklist Go over these before moving on to the backend. They adapt to your framework and your choices: The checklist depends on the framework and the choices. Every combination is listed below. #### React · Vite - **The package is installed**: `@block-auth.io/react` shows up in your frontend `package.json`, not in a new one created elsewhere. - **`BlockAuthProvider` wraps your whole app**: in `src/main.jsx`. - If the apiKey is in an environment variable: **Your apiKey comes from `VITE_BLOCKAUTH_API_KEY`**: in `.env`, read with `import.meta.env.VITE_BLOCKAUTH_API_KEY`. If a change doesn’t apply, restart `npm run dev`. - If the apiKey is written in the widget config: **Your apiKey is in the widget config**: replacing `your_api_key`. - If “Your app today” is “It already has a login”: **The button sits next to your login form**: `` on your login page, reloading the page in `onSuccess`. - If “Your app today” is “It has no login”: **The button is where you want it**: ``, for example in your header. - If “Your app today” is “It already has a login”: **Your logout also closes the Block-Auth session**: with a `POST /auth/blockauth/logout` and a JSON `{}` body, after your own logout. - If “Your app today” is “It has no login”: **The widget handles the logout**: after the login the button becomes the profile menu, with its own sign out. - If the apiKey is in an environment variable: **The `apiSecret` isn’t in the frontend**: not even in a `VITE_…` variable: it only goes in your backend. - If the apiKey is written in the widget config: **The `apiSecret` isn’t in the frontend**: in no frontend file or config: it only goes in your backend. #### React · Next.js - **The package is installed**: `@block-auth.io/react` shows up in your frontend `package.json`, not in a new one created elsewhere. - **`BlockAuthProvider` wraps your whole app**: in `app/providers.jsx`. - If the apiKey is in an environment variable: **Your apiKey comes from `NEXT_PUBLIC_BLOCKAUTH_API_KEY`**: in `.env.local`, read with `process.env.NEXT_PUBLIC_BLOCKAUTH_API_KEY`. If a change doesn’t apply, restart `npm run dev`. - If the apiKey is written in the widget config: **Your apiKey is in the widget config**: replacing `your_api_key`. - If “Your app today” is “It already has a login”: **The button sits next to your login form**: `` on your login page, reloading the page in `onSuccess`. - If “Your app today” is “It has no login”: **The button is where you want it**: ``, for example in your header. - If “Your app today” is “It already has a login”: **Your logout also closes the Block-Auth session**: with a `POST /auth/blockauth/logout` and a JSON `{}` body, after your own logout. - If “Your app today” is “It has no login”: **The widget handles the logout**: after the login the button becomes the profile menu, with its own sign out. - If the apiKey is in an environment variable: **The `apiSecret` isn’t in the frontend**: not even in a `NEXT_PUBLIC_…` variable: it only goes in your backend. - If the apiKey is written in the widget config: **The `apiSecret` isn’t in the frontend**: in no frontend file or config: it only goes in your backend. #### React · Create React App - **The package is installed**: `@block-auth.io/react` shows up in your frontend `package.json`, not in a new one created elsewhere. - **`BlockAuthProvider` wraps your whole app**: in `src/index.js`. - If the apiKey is in an environment variable: **Your apiKey comes from `REACT_APP_BLOCKAUTH_API_KEY`**: in `.env`, read with `process.env.REACT_APP_BLOCKAUTH_API_KEY`. If a change doesn’t apply, restart `npm start`. - If the apiKey is written in the widget config: **Your apiKey is in the widget config**: replacing `your_api_key`. - If “Your app today” is “It already has a login”: **The button sits next to your login form**: `` on your login page, reloading the page in `onSuccess`. - If “Your app today” is “It has no login”: **The button is where you want it**: ``, for example in your header. - If “Your app today” is “It already has a login”: **Your logout also closes the Block-Auth session**: with a `POST /auth/blockauth/logout` and a JSON `{}` body, after your own logout. - If “Your app today” is “It has no login”: **The widget handles the logout**: after the login the button becomes the profile menu, with its own sign out. - If the apiKey is in an environment variable: **The `apiSecret` isn’t in the frontend**: not even in a `REACT_APP_…` variable: it only goes in your backend. - If the apiKey is written in the widget config: **The `apiSecret` isn’t in the frontend**: in no frontend file or config: it only goes in your backend. #### Vue · Vite - **The package is installed**: `@block-auth.io/vue` shows up in your frontend `package.json`, not in a new one created elsewhere. - **`createBlockAuth(...)` is registered**: with `.use()` before `.mount()`, in `src/main.ts` (or `main.js`). - If the apiKey is in an environment variable: **Your apiKey comes from `VITE_BLOCKAUTH_API_KEY`**: in `.env`, read with `import.meta.env.VITE_BLOCKAUTH_API_KEY`. If a change doesn’t apply, restart `npm run dev`. - If the apiKey is written in the widget config: **Your apiKey is in the widget config**: replacing `your_api_key`. - If “Your app today” is “It already has a login”: **The button sits next to your login form**: `` on your login page, reloading the page in `:on-success`. - If “Your app today” is “It has no login”: **The button is where you want it**: ``, for example in your header. - If “Your app today” is “It already has a login”: **Your logout also closes the Block-Auth session**: with a `POST /auth/blockauth/logout` and a JSON `{}` body, after your own logout. - If “Your app today” is “It has no login”: **The widget handles the logout**: after the login the button becomes the profile menu, with its own sign out. - If the apiKey is in an environment variable: **The `apiSecret` isn’t in the frontend**: not even in a `VITE_…` variable: it only goes in your backend. - If the apiKey is written in the widget config: **The `apiSecret` isn’t in the frontend**: in no frontend file or config: it only goes in your backend. #### Angular - **The package is installed**: `@block-auth.io/angular` shows up in your frontend `package.json`, not in a new one created elsewhere. - **`angular.json` has the widget dependencies**: `allowedCommonJsDependencies` and `externalDependencies` in the build options, and an `initial` budget of 2 MB in production. - **`provideBlockAuth(...)` is in your providers**: in `src/app/app.config.ts`. - If the apiKey is in an environment variable: **Your apiKey comes from `environment.blockauthApiKey`**: in `src/environments/environment.ts`, imported in `app.config.ts`. - If the apiKey is written in the widget config: **Your apiKey is in the widget config**: replacing `your_api_key`. - If “Your app today” is “It already has a login”: **The button sits next to your login form**: `` on your login page, reloading the page in `(success)`. - If “Your app today” is “It has no login”: **The button is where you want it**: ``, for example in your header. - If “Your app today” is “It already has a login”: **Your logout also closes the Block-Auth session**: with a `POST /auth/blockauth/logout` and a JSON `{}` body, after your own logout. - If “Your app today” is “It has no login”: **The widget handles the logout**: after the login the button becomes the profile menu, with its own sign out. - If the apiKey is in an environment variable: **The `apiSecret` isn’t in the frontend**: not even in `environment.ts`: it only goes in your backend. - If the apiKey is written in the widget config: **The `apiSecret` isn’t in the frontend**: in no frontend file or config: it only goes in your backend. Login doesn’t work yet: your backend is missing. You test it end to end in the last step, [Connect and try it](/sdk-integration-spa-connect.md#try-it). Next step: [Your backend](/sdk-integration-spa-backend.md) --- title: "React, Vue or Angular: your backend" description: "Add the routes the widget calls and receive webhooks, with the Block-Auth package for your server or with your own implementation." url: "/sdk-integration-spa-backend/" language: "en" guide: "React, Vue, Angular (+ backend)" step: "Quickstart step 2 of 4, required" --- # Your backend Add the routes the widget calls and receive webhooks. With the Block-Auth package for your server it's mostly configuration: it redeems the login code, keeps the session and verifies the webhooks for you. If you prefer, you can write it yourself. ## Your environment variables Your backend reads these variables. Here they are with your data: `APP_URL` in development is the URL where your frontend runs: Vite `http://localhost:5173`, Next.js `http://localhost:3000`, Create React App `http://localhost:3000`, Angular `http://localhost:4200`. #### Node.js · development In a .env next to your backend package.json. Load it with `node --env-file=.env` (Node 20.6+) or the `dotenv` package (`import 'dotenv/config'` at the top of your entry file). **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Node.js · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### PHP · development getenv() doesn't read .env files by itself: set them in your server (`SetEnv` in Apache, `env[]` in PHP-FPM), or load the .env with `vlucas/phpdotenv`. **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= ``` #### PHP · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= ``` #### Python (Flask) · development In a .env in your backend folder. `flask run` loads it if `python-dotenv` is installed; with `python app.py`, gunicorn or waitress, call `load_dotenv()` first, use `uv run --env-file .env …` or export the variables. **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Python (Flask) · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Python (FastAPI) · development In a .env in your backend folder. Start uvicorn with `--env-file .env` (needs `python-dotenv` installed) or, with uv, `uv run --env-file .env uvicorn …`, or export the variables. **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Python (FastAPI) · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### .NET · development The public values go in `appsettings.json`. The secret never goes in a file you commit: in development use `user-secrets`, in production an environment variable. **appsettings.json** ```json { "APP_URL": "http://localhost:5173", "BLOCKAUTH_API_KEY": "your_api_key" } ``` **Terminal, in the project folder (development only)** ```bash dotnet user-secrets init dotnet user-secrets set "BLOCKAUTH_API_SECRET" "" ``` #### .NET · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **appsettings.json** ```json { "APP_URL": "https://your-app.com", "BLOCKAUTH_API_KEY": "your_api_key" } ``` **Environment variable on your server (never in a repo file)** ```dotenv BLOCKAUTH_API_SECRET= ``` > **Placeholders in this code:** > > - Replace the API Secret placeholder with your API Secret, copied straight from the Dashboard. Never paste it on this site. > - Replace the SESSION\_SECRET placeholder with a random value generated on your computer: `openssl rand -hex 32`. > - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you. > - Replace `https://your-app.com` with your app URL, or fill in your data in the SDK Quickstart and it is filled in for you. > How you add the backend login routes: this page covers “With the Block-Auth package” or “My own implementation”. Both variants are written out below, each one marked. Follow only the one that matches the app. ## Add the backend routes ### How you add the backend login routes: With the Block-Auth package. ### 1. Install the package **Only for Node.js:** Run it next to your backend’s `package.json` (if your frontend and backend share one project, at the root): **Node.js · Terminal · next to your backend package.json** ```bash npm install @block-auth.io/node ``` **Only for PHP:** Run it next to your backend’s `composer.json` (if your frontend and backend share one project, at the root): **PHP · Terminal · next to your backend composer.json** ```bash composer require blockauth/sdk ``` **Only for .NET:** Run it next to your backend’s `.csproj` (if your frontend and backend share one project, at the root): **.NET · Terminal · next to your backend .csproj** ```bash dotnet add package BlockAuth.Sdk.AspNetCore ``` **Only for Python (Flask):** **Only for pip:** Run it next to your backend’s `requirements.txt`, with its virtual environment active (if your frontend and backend share one project, at the root): **Python (Flask) · Terminal · next to your backend requirements.txt** ```bash source .venv/bin/activate pip install "blockauth-sdk[flask]" ``` Also add `blockauth-sdk[flask]` (without quotes) to your `requirements.txt` so your deployment installs it. If `pip` answers `externally-managed-environment`, your backend’s virtual environment isn’t active. **Only for uv:** Run it next to your backend’s `pyproject.toml` (if your frontend and backend share one project, at the root): **Python (Flask) · Terminal · next to your backend pyproject.toml** ```bash uv add "blockauth-sdk[flask]" ``` `uv add` already saves it in your `pyproject.toml` and lock file, so your deployment installs it. **Only for Poetry:** Run it next to your backend’s `pyproject.toml` (if your frontend and backend share one project, at the root): **Python (Flask) · Terminal · next to your backend pyproject.toml** ```bash poetry add "blockauth-sdk[flask]" ``` `poetry add` already saves it in your `pyproject.toml` and lock file, so your deployment installs it. **Only for Python (FastAPI):** **Only for pip:** Run it next to your backend’s `requirements.txt`, with its virtual environment active (if your frontend and backend share one project, at the root): **Python (FastAPI) · Terminal · next to your backend requirements.txt** ```bash source .venv/bin/activate pip install "blockauth-sdk[fastapi]" ``` Also add `blockauth-sdk[fastapi]` (without quotes) to your `requirements.txt` so your deployment installs it. If `pip` answers `externally-managed-environment`, your backend’s virtual environment isn’t active. **Only for uv:** Run it next to your backend’s `pyproject.toml` (if your frontend and backend share one project, at the root): **Python (FastAPI) · Terminal · next to your backend pyproject.toml** ```bash uv add "blockauth-sdk[fastapi]" ``` `uv add` already saves it in your `pyproject.toml` and lock file, so your deployment installs it. **Only for Poetry:** Run it next to your backend’s `pyproject.toml` (if your frontend and backend share one project, at the root): **Python (FastAPI) · Terminal · next to your backend pyproject.toml** ```bash poetry add "blockauth-sdk[fastapi]" ``` `poetry add` already saves it in your `pyproject.toml` and lock file, so your deployment installs it. **Only for Node.js:** ### Your app today: It already has a login. The package works with Express and `express-session`. Check your `package.json` dependencies: if you already have both, skip this. If one is missing, install it: `npm install express express-session`. ### Your app today: It has no login. The package works with Express and `express-session`. If your server doesn’t have them yet, install them too: `npm install express express-session`. **Only for Python (Flask):** ### Your app today: It already has a login. The package keeps the user in Flask’s session, which needs `app.secret_key`. Search your code for `secret_key`: if your app already sets it, skip this and the package will use that same session. If not, add `app.secret_key = os.environ["SESSION_SECRET"]` right after `app = Flask(...)`. ### Your app today: It has no login. The package keeps the user in Flask’s session, which needs `app.secret_key`. If your app doesn’t set it yet, add `app.secret_key = os.environ["SESSION_SECRET"]` right after `app = Flask(...)`. **Only for Python (FastAPI):** ### Your app today: It already has a login. The package keeps the user in Starlette’s session. Search your code for `SessionMiddleware`: if your app already adds it, skip this and the block below, because the package will use that same session. If not, add it right after `app = FastAPI()`: ### Your app today: It has no login. The package keeps the user in Starlette’s session. If your app doesn’t have `SessionMiddleware` yet, add it right after `app = FastAPI()`: **Python (FastAPI) · Only if you don’t have it · right after app = FastAPI()** ```python from starlette.middleware.sessions import SessionMiddleware app.add_middleware( SessionMiddleware, secret_key=os.environ["SESSION_SECRET"], same_site="lax", https_only=os.environ["APP_URL"].startswith("https"), ) ``` ### 2. Add it to your server This is **everything you add** to your server, in three parts. Your app, your session and your server start-up stay as they are. **a. The imports**, at the top of the file where you create your app, next to the ones you already have: **Node.js · Top of the file · with your imports** ```javascript import { BlockAuthRoutes } from '@block-auth.io/node' import { blockauthRouter } from '@block-auth.io/node/express' ``` **PHP · public/index.php · at the top, after the autoload** ```php use BlockAuth\Routes\BlockAuthRoutes; ``` **Python (Flask) · Top of the file · with your imports** ```python import os from blockauth_sdk import BlockAuthRoutes from blockauth_sdk.routes.flask import blockauth_blueprint ``` **Python (FastAPI) · Top of the file · with your imports** ```python import os from blockauth_sdk import BlockAuthRoutes from blockauth_sdk.routes.fastapi import blockauth_router ``` **.NET · Program.cs · at the very top** ```csharp using BlockAuth.AspNetCore; ``` **Only for Python (Flask), Python (FastAPI):** You only need `import os` if step b reads the keys with `os.environ`. If your app reads them from its own configuration file (a `config.py`, a `Settings` class…), don’t add it. **Only for Node.js, PHP, Python (Flask), Python (FastAPI):** **b. Create `routes`.** Don’t paste your keys here: the block reads them from the `.env` you filled in under “Your environment variables”, so the API Secret never ends up in your code. Where it goes, right below the block: **Only for .NET:** **b. Register Block-Auth** before `var app = builder.Build();`: **Node.js · Below const app = express()** ```javascript export const routes = new BlockAuthRoutes({ apiKey: process.env.BLOCKAUTH_API_KEY, apiSecret: process.env.BLOCKAUTH_API_SECRET, appUrl: process.env.APP_URL, }) ``` **PHP · public/index.php · before your router** ```php $routes = new BlockAuthRoutes(getenv('BLOCKAUTH_API_KEY'), getenv('BLOCKAUTH_API_SECRET'), [ 'appUrl' => getenv('APP_URL'), ]); ``` **Python (Flask) · Below app = Flask(...)** ```python routes = BlockAuthRoutes( os.environ["BLOCKAUTH_API_KEY"], os.environ["BLOCKAUTH_API_SECRET"], app_url=os.environ["APP_URL"], ) ``` **Python (FastAPI) · Below app = FastAPI()** ```python routes = BlockAuthRoutes( os.environ["BLOCKAUTH_API_KEY"], os.environ["BLOCKAUTH_API_SECRET"], app_url=os.environ["APP_URL"], ) ``` **.NET · Program.cs · before builder.Build()** ```csharp builder.Services.AddBlockAuth(options => { options.ApiKey = builder.Configuration["BLOCKAUTH_API_KEY"]!; options.ApiSecret = builder.Configuration["BLOCKAUTH_API_SECRET"]!; options.AppUrl = builder.Configuration["APP_URL"]; }); builder.Services.AddAuthorization(); ``` **Only for Node.js:** **Where to put it:** in the file with `const app = express()`, right below that line. Two adjustments, only if your code looks like this: - **That line is inside a function**, like `function createApp(config) {`: put the block inside the function, also below it, and drop the `export`. If you leave it outside, importing the file without the variables (from a test, for example) fails with `Set appUrl or allowedOrigins`. If your tests create the app with their own configuration, give them test values too, like `appUrl: 'http://localhost'`, or they fail with that same error. - **Your app reads `SESSION_SECRET` from a configuration file** (a `config.js`, an `env.ts`, a zod schema…): add `BLOCKAUTH_API_KEY`, `BLOCKAUTH_API_SECRET` and `APP_URL` there too, and in the block change each `process.env.…` to your configuration value (for example, `config.blockauthApiKey`). The block still goes below `const app = express()`. If you see `Set appUrl or allowedOrigins` on startup, the variables aren’t reaching your server: check that it loads the `.env` (for example, with `node --env-file=.env`, Node 20.6+, or with `import 'dotenv/config'` at the top of your entry file). **Only for PHP:** **Where to put it:** in `public/index.php`, before your router. If your app reads `SESSION_SECRET` from a configuration file (for example, a `config.php` that returns an array), add `BLOCKAUTH_API_KEY`, `BLOCKAUTH_API_SECRET` and `APP_URL` there too, and in the block change each `getenv(…)` to your configuration value. If `getenv` returns `false`, the variables aren’t reaching PHP: load the `.env` before this block (for example, with `vlucas/phpdotenv`) or define them in your web server or container. **Only for Python (Flask), Python (FastAPI):** **Only for Python (Flask):** **Where to put it:** in the file with `app = Flask(...)`, right below that line. Two adjustments, only if your code looks like this: **Only for Python (FastAPI):** **Where to put it:** in the file with `app = FastAPI()`, right below that line. Two adjustments, only if your code looks like this: - **That line is inside a function**, like `def create_app()` or `def create_app(config)`: put the block inside the function, also below it. If you leave it outside, importing the file without the variables (from a test, for example) fails with `Set app_url or allowed_origins`. If your tests create the app with their own configuration, give them test values too, like `app_url="http://testserver"`, or they fail with that same error. - **Your app reads `SESSION_SECRET` from a configuration file** (a `config.py`, a `Settings` class, Flask’s `app.config`…): add `BLOCKAUTH_API_KEY`, `BLOCKAUTH_API_SECRET` and `APP_URL` there too, and in the block change each `os.environ[…]` to your configuration value (for example, `config.blockauth_api_key`). The block still goes below the app line, and you no longer need the `import os` from step a. **Only for Python (Flask):** If you see `KeyError: 'BLOCKAUTH_API_KEY'` or `Set app_url or allowed_origins` on startup, the variables aren’t reaching your server: `flask run` only loads the `.env` when `python-dotenv` is installed; with `python app.py` or gunicorn, call `load_dotenv()` first or start with `uv run --env-file .env …`. **Only for Python (FastAPI):** If you see `KeyError: 'BLOCKAUTH_API_KEY'` or `Set app_url or allowed_origins` on startup, the variables aren’t reaching your server: start uvicorn with `--env-file .env` (needs `python-dotenv` installed) or, with uv, `uv run --env-file .env uvicorn …`; you can also load it in your configuration module or export them before starting. If uvicorn answers `No module named 'dotenv'`, install `python-dotenv` or use `uv run --env-file`. **Only for Node.js:** **Before mounting it, search for `session(` in your file.** If it’s on its own, in `app.use(session(...))`, change nothing: in step c you put the line right below it. If it’s inside an `app.use('/api', …)` together with other things, like `express.json()`, it only covers `/api` and Block-Auth can’t see it. Split it like this: the session leaves the `app.use('/api', …)` with its options as they are, Block-Auth goes right below it and the rest stays under `/api`: **Before · Everything together under /api (example only, not to copy)** ```javascript app.use( '/api', express.json(), session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: 'lax' }, }), ) ``` **After · The session leaves /api · Block-Auth below** ```javascript app.use( session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: 'lax' }, }), ) app.use(blockauthRouter(routes)) app.use('/api', express.json()) ``` **Only for Node.js, PHP, Python (Flask), Python (FastAPI):** **c. Mount it** in your app. This is the part where placement matters most. Put it where `routes` already exists: after step b and in the same place. If you created `routes` inside a function, like `createApp()` or `create_app()`, this line goes inside that same function. In Python that means with the same indentation as the `routes = ...` line; if you paste it against the left margin, it ends up outside the function and Python raises an error: **Only for .NET:** **c. Mount it** after `var app = builder.Build();`: **Node.js · Right below where you mount session(...)** ```javascript app.use(blockauthRouter(routes)) ``` **PHP · Right after · before your router** ```php if ($routes->handle()) { exit; } ``` **Python (Flask) · After app = Flask(...) · or inside create\_app()** ```python app.register_blueprint(blockauth_blueprint(routes)) ``` **Python (FastAPI) · After app = FastAPI() · next to your routers** ```python app.include_router(blockauth_router(routes)) ``` **.NET · Program.cs · after builder.Build()** ```csharp app.UseAuthentication(); app.UseAuthorization(); app.MapBlockAuth(); ``` **Only for Node.js:** **Put it before serving your frontend** (`express.static(...)`) **and before any catch-all route** (`app.get('*', …)`). If those come first, they take the widget’s requests and Block-Auth never sees them: you get no error, just a 404 or your app’s HTML. **Only for Python (Flask):** **Put it before any catch-all route** (like `@app.route("/")`) **and before serving your frontend**. If those come first, they take the widget’s requests and Block-Auth never sees them: you get no error, just a 404 or your app’s HTML. **Only for Python (FastAPI):** **Put it before any catch-all route** (like `/api/{path:path}`) **and before `app.mount("/", ...)`** if FastAPI serves your frontend. If those come first, they take the widget’s requests and Block-Auth never sees them: you get no error, just a 404 or your app’s HTML. ### 3. Checklist Go over these before moving on. They’re what most often fails when adding it to an existing app: **Checklist for Node.js:** - **The session covers the whole app**: `app.use(session(...))`, not just `/api`. - **The order is** session → `blockauthRouter` → `express.json()`. - **You load the `.env`**: `node --env-file=.env` (Node 20.6+) or the `dotenv` package (`import 'dotenv/config'` at the top of your entry file). - **Behind a proxy that terminates `https`**, add `app.set('trust proxy', 1)`. **Checklist for PHP:** - **`handle()` goes at the top**, before your router and any output. - **You load the `.env`**: `getenv()` doesn’t read it by itself. Use your web server or `vlucas/phpdotenv`. - **Laravel or Symfony?** Call `$routes->dispatch(...)` from a route, pass your session with the `session` option and exclude `/auth/blockauth/*` from CSRF. **Checklist for Python (Flask):** - **`app.secret_key` is set**: Flask’s session needs it. - **`register_blueprint` goes after you create `app`**, or inside `create_app()`. - **You load the `.env`**: `flask run` with `python-dotenv` installed; with `python app.py` or gunicorn, `load_dotenv()` on startup or `uv run --env-file .env …`. - **Using `CSRFProtect`?** Exempt the blueprint with `csrf.exempt(...)`. **Checklist for Python (FastAPI):** - **You have `SessionMiddleware`**, once: `app.add_middleware(SessionMiddleware, secret_key=...)`. - **`include_router` goes after you create `app`**. - **You load the `.env`**: `uvicorn main:app --env-file .env` (with `python-dotenv` installed) or `uv run --env-file .env uvicorn main:app`. **Checklist for .NET:** - **`AddBlockAuth` goes before `builder.Build()`**. - **`UseAuthentication()` and `UseAuthorization()` go before `MapBlockAuth()`**, without repeating them. - **You don’t need `AddSession`**: it uses its own cookie and leaves your authentication alone. This only checks that everything is in place. The real test comes in the last step, [Connect and try it](/sdk-integration-spa-connect.md#try-it). ### How you add the backend login routes: My own implementation. Any server, in any language, can do it with plain HTTP. Send the **SHA-256 hash (hex)** of your `apiSecret`, never the secret itself. The examples use the `AuthCodeClient` of each Block-Auth client library; in Node.js they call the API with `fetch`. Install it where your backend’s `package.json`, `composer.json`, `requirements.txt` or `.csproj` is: **Node.js · Terminal · only if your server doesn’t have them yet** ```bash npm install express express-session ``` **PHP · Terminal · next to your backend composer.json** ```bash composer require blockauth/sdk ``` **Python · Terminal · with your backend environment active** ```bash pip install blockauth-sdk flask ``` **.NET · Terminal · next to your backend .csproj** ```bash dotnet add package BlockAuth.Sdk ``` In `POST /code`, redeem the code the widget sends you: **Redeem the code · Terminal · to try it** ```bash curl -X POST https://wss.block-auth.io/api/auth/token \ -H 'Content-Type: application/json' \ -d '{ "apiKey": "your_api_key", "apiSecret": "sha256_hex_of_your_api_secret", "code": "code_from_the_widget", "codeVerifier": "code_verifier_from_the_widget", "redirectUri": "redirect_uri_from_the_widget" }' ``` > **Placeholders in this code:** > > - Replace the `sha256_…` value with the SHA-256 hash (hex) of your API Secret. Compute it on your computer, never on a web page. > - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you. > - Replace the `…_from_the_widget` values with the ones the widget sends to your `/code` route. Every response is `{ "success": true, "message": … }`; for `/api/auth/token`, `message` holds `address`, `did` and `roles`. To verify a webhook, compute `v1=` + HMAC-SHA256 of `timestamp.body` (the `X-BlockAuth-Timestamp` header, a dot and the raw body), keyed with the SHA-256 hash of your `apiSecret`, and compare it with `X-BlockAuth-Signature`. All the parameters and errors are in [User login](/api-user-login.md). Then add these routes under `/auth/blockauth`, or under your `authEndpoint` if you changed it in [Configure the widget](/sdk-integration-spa-frontend.md#config-options). The examples are a complete server. **If you already have a server**, copy only the Block-Auth client (the start of each example) and the three routes: you already have your session and your server start-up. The session must cover `/auth/blockauth`, and in Node.js the webhook route (below) must come before a global `express.json()`: | Route | Receives | Responds | | -------------- | ------------------------------------- | ---------------------------------------------------------- | | `POST /code` | `{ code, codeVerifier, redirectUri }` | `{ address, did, roles }` and sets your session cookie | | `GET /me` | — | `{ address, did, roles }`, or `401` if there is no session | | `POST /logout` | — | `200` and clears your session | > **Note:** Two things the example takes for granted, and that aren’t green because your app usually has them already. Check that you have them: > > - **Your router**: the example routes its own way (in PHP, with `if ($route === …)`). If your app already has a router, add the routes to it. > - **The session open before these routes**: `/code` keeps the user in the session and `/me` reads it. If your app opens the session only when it needs it, open it before these routes too (in PHP, `session_start()`). **Node.js · server.js · or where you create app = express()** ```javascript import crypto from 'node:crypto' import express from 'express' import session from 'express-session' const API = 'https://wss.block-auth.io/api' const { APP_URL, BLOCKAUTH_API_KEY, BLOCKAUTH_API_SECRET, SESSION_SECRET } = process.env const API_SECRET_HASH = crypto.createHash('sha256').update(BLOCKAUTH_API_SECRET).digest('hex') export async function blockauth(path, body) { const res = await fetch(`${API}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ apiKey: BLOCKAUTH_API_KEY, apiSecret: API_SECRET_HASH, ...body }), signal: AbortSignal.timeout(10000), }) const payload = await res.json().catch(() => ({})) if (!res.ok || !payload.success) throw new Error(payload.message || `Block-Auth ${res.status}`) return payload.message } const sessionUser = (user) => ({ address: user.address, did: user.did, roles: user.roles, expiresAt: Date.parse(`${user.signedExpiredAt.replace(' ', 'T')}Z`), }) export const currentUser = (req) => { const user = req.session.user if (user && Date.now() < user.expiresAt) return user delete req.session.user return null } const isOwnUrl = (value) => { try { return new URL(value).origin === new URL(APP_URL).origin } catch { return false } } export const app = express() app.use( session({ secret: SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: 'lax', secure: APP_URL.startsWith('https') }, }), ) app.post('/auth/blockauth/code', express.json(), async (req, res) => { const { code, codeVerifier, redirectUri } = req.body ?? {} if (typeof code !== 'string' || typeof codeVerifier !== 'string' || !isOwnUrl(redirectUri)) { return res.status(400).json({ error: 'invalid_request' }) } try { const user = await blockauth('/auth/token', { code, codeVerifier, redirectUri }) req.session.regenerate((err) => { if (err) return res.status(500).end() req.session.user = sessionUser(user) res.json({ address: user.address, did: user.did, roles: user.roles }) }) } catch { res.status(502).json({ error: 'blockauth_error' }) } }) app.get('/auth/blockauth/me', (req, res) => { const user = currentUser(req) if (!user) return res.status(401).json({ error: 'unauthenticated' }) res.json({ address: user.address, did: user.did, roles: user.roles }) }) app.post('/auth/blockauth/logout', async (req, res) => { const user = req.session.user if (user) await blockauth('/auth/signout', { address: user.address }).catch(() => {}) req.session.destroy(() => res.json({ ok: true })) }) app.listen(4000) ``` **PHP · public/index.php · at the top, before your router** ```php true, 'cookie_samesite' => 'Lax', 'cookie_secure' => str_starts_with($appUrl, 'https'), ]); $blockauth = new AuthCodeClient(getenv('BLOCKAUTH_API_KEY'), getenv('BLOCKAUTH_API_SECRET')); function json(int $status, array $body): void { http_response_code($status); header('Content-Type: application/json'); echo json_encode($body); exit; } function currentUser(): ?array { $user = $_SESSION['user'] ?? null; if ($user && time() < $user['expires_at']) { return $user; } unset($_SESSION['user']); return null; } function isOwnUrl(string $value, string $appUrl): bool { $origin = fn ($url) => parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . (parse_url($url, PHP_URL_PORT) ? ':' . parse_url($url, PHP_URL_PORT) : ''); return filter_var($value, FILTER_VALIDATE_URL) !== false && $origin($value) === $origin($appUrl); } $route = $_SERVER['REQUEST_METHOD'] . ' ' . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); if ($route === 'POST /auth/blockauth/code') { $body = json_decode(file_get_contents('php://input'), true) ?: []; $code = $body['code'] ?? null; $verifier = $body['codeVerifier'] ?? null; $redirectUri = $body['redirectUri'] ?? ''; if (!is_string($code) || !is_string($verifier) || !isOwnUrl($redirectUri, $appUrl)) { json(400, ['error' => 'invalid_request']); } try { $user = $blockauth->exchangeCode($code, $redirectUri, $verifier); } catch (BlockAuthException $e) { json(502, ['error' => 'blockauth_error']); } session_regenerate_id(true); $_SESSION['user'] = [ 'address' => $user['address'], 'did' => $user['did'], 'roles' => $user['roles'], 'expires_at' => strtotime($user['signedExpiredAt'] . ' UTC'), ]; json(200, ['address' => $user['address'], 'did' => $user['did'], 'roles' => $user['roles']]); } if ($route === 'GET /auth/blockauth/me') { $user = currentUser(); if (!$user) { json(401, ['error' => 'unauthenticated']); } json(200, ['address' => $user['address'], 'did' => $user['did'], 'roles' => $user['roles']]); } if ($route === 'POST /auth/blockauth/logout') { $user = $_SESSION['user'] ?? null; if ($user) { try { $blockauth->signOut($user['address']); } catch (BlockAuthException $e) { } } session_destroy(); json(200, ['ok' => true]); } ``` **Python · app.py · or where you create app = Flask(...)** ```python import os from datetime import datetime, timezone from urllib.parse import urlsplit from flask import Flask, jsonify, request, session from blockauth_sdk import AuthCodeClient, BlockAuthError APP_URL = os.environ["APP_URL"] app = Flask(__name__) app.secret_key = os.environ["SESSION_SECRET"] app.config.update(SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Lax", SESSION_COOKIE_SECURE=APP_URL.startswith("https")) blockauth = AuthCodeClient(os.environ["BLOCKAUTH_API_KEY"], os.environ["BLOCKAUTH_API_SECRET"]) def session_user(user): expires_at = datetime.strptime(user["signedExpiredAt"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc) return {"address": user["address"], "did": user["did"], "roles": user["roles"], "expires_at": expires_at.timestamp()} def current_user(): user = session.get("user") if user and datetime.now(timezone.utc).timestamp() < user["expires_at"]: return user session.pop("user", None) return None def is_own_url(value): if not isinstance(value, str): return False url, app_url = urlsplit(value), urlsplit(APP_URL) return (url.scheme, url.netloc) == (app_url.scheme, app_url.netloc) @app.post("/auth/blockauth/code") def redeem_code(): body = request.get_json(silent=True) or {} code, verifier, redirect_uri = body.get("code"), body.get("codeVerifier"), body.get("redirectUri") if not isinstance(code, str) or not isinstance(verifier, str) or not is_own_url(redirect_uri): return jsonify(error="invalid_request"), 400 try: user = blockauth.exchange_code(code, redirect_uri, code_verifier=verifier) except BlockAuthError: return jsonify(error="blockauth_error"), 502 session.clear() session["user"] = session_user(user) return jsonify(address=user["address"], did=user["did"], roles=user["roles"]) @app.get("/auth/blockauth/me") def me(): user = current_user() if not user: return jsonify(error="unauthenticated"), 401 return jsonify(address=user["address"], did=user["did"], roles=user["roles"]) @app.post("/auth/blockauth/logout") def logout(): user = session.get("user") if user: try: blockauth.sign_out(user["address"]) except BlockAuthError: pass session.clear() return jsonify(ok=True) ``` **.NET · Program.cs** ```csharp using System.Globalization; using System.Text.Json; using BlockAuth; using BlockAuth.Exceptions; var builder = WebApplication.CreateBuilder(args); builder.Services.AddDistributedMemoryCache(); builder.Services.AddSession(options => { options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Lax; options.Cookie.SecurePolicy = builder.Configuration["APP_URL"]!.StartsWith("https") ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest; }); builder.Services.AddSingleton(new AuthCodeClient( builder.Configuration["BLOCKAUTH_API_KEY"]!, builder.Configuration["BLOCKAUTH_API_SECRET"]!)); var app = builder.Build(); app.UseSession(); string? CurrentAddress(HttpContext http) { var expiresAt = http.Session.GetString("expires_at"); var valid = expiresAt is not null && DateTime.ParseExact(expiresAt, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal) > DateTime.UtcNow; if (valid) return http.Session.GetString("address"); http.Session.Clear(); return null; } var appOrigin = new Uri(builder.Configuration["APP_URL"]!).GetLeftPart(UriPartial.Authority); bool IsOwnUrl(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.GetLeftPart(UriPartial.Authority) == appOrigin; app.MapPost("/auth/blockauth/code", async (CodeRequest body, HttpContext http, AuthCodeClient blockauth) => { if (string.IsNullOrEmpty(body.Code) || string.IsNullOrEmpty(body.CodeVerifier) || !IsOwnUrl(body.RedirectUri)) return Results.BadRequest(new { error = "invalid_request" }); try { var user = await blockauth.ExchangeCodeAsync(body.Code, body.RedirectUri!, body.CodeVerifier); http.Session.Clear(); http.Session.SetString("address", user.Address); http.Session.SetString("did", user.Did ?? user.Address); http.Session.SetString("roles", user.Roles.GetRawText()); http.Session.SetString("expires_at", user.SignedExpiredAt); return Results.Ok(new { address = user.Address, did = user.Did ?? user.Address, roles = user.Roles }); } catch (BlockAuthException) { return Results.Json(new { error = "blockauth_error" }, statusCode: 502); } }); app.MapGet("/auth/blockauth/me", (HttpContext http) => { var address = CurrentAddress(http); if (address is null) return Results.Json(new { error = "unauthenticated" }, statusCode: 401); var roles = JsonDocument.Parse(http.Session.GetString("roles") ?? "[]").RootElement.Clone(); return Results.Ok(new { address, did = http.Session.GetString("did") ?? address, roles }); }); app.MapPost("/auth/blockauth/logout", async (HttpContext http, AuthCodeClient blockauth) => { var address = http.Session.GetString("address"); if (address is not null) { try { await blockauth.SignOutAsync(address); } catch (BlockAuthException) { } } http.Session.Clear(); return Results.Ok(new { ok = true }); }); app.Run(); record CodeRequest(string? Code, string? CodeVerifier, string? RedirectUri); ``` > **Placeholders in this code:** > > - The `app.listen(…)` port is the Backend port from your data. If your server already starts, keep your own `listen`. > **Note:** The code is valid for 60 seconds and can be redeemed only once. Calling > `/api/auth/signout` on logout also closes the user's Block-Auth sessions for > your app on every device. Your session ends when the user's Block-Auth signature does: `signedExpiredAt`, in UTC with the format `YYYY-MM-DD HH:mm:ss`. That's why the session keeps that moment and every route checks it before trusting the user ([how long a session lasts](/security.md#session)). Next step: [Connect and try it](/sdk-integration-spa-connect.md) --- title: "React, Vue or Angular: connect and try it" description: "Connect your frontend to your backend and check that login works." url: "/sdk-integration-spa-connect/" language: "en" guide: "React, Vue, Angular (+ backend)" step: "Quickstart step 3 of 4, required" --- # Connect and try it The last step: make your frontend reach your backend, and check that login works end to end. ## Connect your frontend to your backend **In development (localhost):** The widget calls `/auth/blockauth` on the **same origin** as your page, so the session cookie travels with every request. In development your frontend (your App URL) and backend usually run on different ports: proxy those routes to the port your backend already listens on, with your dev server’s proxy: #### React · Vite **vite.config.js · at your frontend root · add only server.proxy** ```javascript import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { proxy: { '/auth/blockauth': 'http://localhost:4000' }, }, }) ``` #### React · Next.js **next.config.js · at the project root · add only rewrites** ```javascript const nextConfig = { async rewrites() { if (process.env.NODE_ENV !== 'development') return [] return [{ source: '/auth/blockauth/:path*', destination: 'http://localhost:4000/auth/blockauth/:path*' }] }, } export default nextConfig ``` #### React · Create React App **package.json · of your frontend · add only "proxy"** ```json { "proxy": "http://localhost:4000" } ``` #### Vue · Vite **vite.config.js · at your frontend root · add only server.proxy** ```javascript import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], server: { proxy: { '/auth/blockauth': 'http://localhost:4000' }, }, }) ``` #### Angular **proxy.conf.json · new file at your frontend root** ```json { "/auth/blockauth": { "target": "http://localhost:4000", "secure": false } } ``` **Terminal · start the frontend with the proxy** ```bash ng serve --proxy-config proxy.conf.json ``` > Only for development. `4000` is the port your backend already listens on: change it in your data if it isn’t. > > Use the port your backend already listens on. Defaults in the examples: Node.js `4000`, PHP `8080`, Python (Flask) `5000`, Python (FastAPI) `8000`, .NET `5000`. This isn’t used in production: with Production in your settings, this section shows how to serve it from your domain. **In production (your domain):** The widget calls `/auth/blockauth` on the **same origin** as your page, so the session cookie travels with every request. In production you get that by serving everything from your domain, in one of these two ways: - **Your backend serves the frontend build.** Build it (`npm run build`) and have your backend serve that folder. Nothing else needed. - **Frontend and backend run separately.** Your reverse proxy sends `/auth/blockauth` to your backend. For example, with Nginx: **Nginx · Your web server · add the location to your server block** ```nginx server { server_name your-app.com; location /auth/blockauth/ { proxy_pass http://127.0.0.1:4000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } ``` > **Placeholders in this code:** > > - Replace `your-app.com` with your domain, or fill in your data in the SDK Quickstart and it is filled in for you. > - `127.0.0.1` is your own server: change it if your backend runs on another machine. The port is the Backend port from your data, the one your server already uses. With `https` on a proxy in front, your backend must know it to send the secure cookie: see [Go live](/sdk-integration-spa-go-live.md#production-domain). ## Try it 1. **In development (localhost):** Start your frontend and your backend. **In production (your domain):** Deploy your frontend and your backend on your domain. 2. Open your app, press the Block-Auth button and sign in. 3. Open `https://your-app.com/auth/blockauth/me` in the same browser: it must return your user. **If it does, it works in development.** The last step is [Go live](/sdk-integration-spa-go-live.md): the same, with your production keys and domain. If it doesn’t work: - **You see your app’s page or a `404`**: the request doesn’t reach your backend. Check the connection above and that your backend is running. - **`401` after signing in**: the login didn’t create the session. Go over your [backend checklist](/sdk-integration-spa-backend.md#server-checks). Next step: [Go live](/sdk-integration-spa-go-live.md) --- title: "React, Vue or Angular: go live" description: "The checks before publishing your integration." url: "/sdk-integration-spa-go-live/" language: "en" guide: "React, Vue, Angular (+ backend)" step: "Quickstart step 4 of 4, required" --- # Go live Your code doesn’t change: only the keys, the variables and the domain do. Here are just those changes, with your production data. Every example on this page uses the production values: the production API Key and API Secret and the app’s real domain. ## What changes ### 1. Validate your domain and use the Production keys In the Dashboard, [validate your domain](/integration-quickstart.md#apps-validate-domain). Then copy the **Production** data with **Copy data for the guide** and paste it into [your data](/sdk-integration.md#setup): it fills in the Production row. ### 2. Put the variables on your server In production don’t use your computer’s `.env`: set them as environment variables on your server or platform (Docker, your hosting…). Generate a new `SESSION_SECRET`, different from the development one. `APP_URL` in development is the URL where your frontend runs: Vite `http://localhost:5173`, Next.js `http://localhost:3000`, Create React App `http://localhost:3000`, Angular `http://localhost:4200`. #### Node.js · development In a .env next to your backend package.json. Load it with `node --env-file=.env` (Node 20.6+) or the `dotenv` package (`import 'dotenv/config'` at the top of your entry file). **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Node.js · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### PHP · development getenv() doesn't read .env files by itself: set them in your server (`SetEnv` in Apache, `env[]` in PHP-FPM), or load the .env with `vlucas/phpdotenv`. **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= ``` #### PHP · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= ``` #### Python (Flask) · development In a .env in your backend folder. `flask run` loads it if `python-dotenv` is installed; with `python app.py`, gunicorn or waitress, call `load_dotenv()` first, use `uv run --env-file .env …` or export the variables. **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Python (Flask) · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Python (FastAPI) · development In a .env in your backend folder. Start uvicorn with `--env-file .env` (needs `python-dotenv` installed) or, with uv, `uv run --env-file .env uvicorn …`, or export the variables. **Your backend’s .env · in your backend folder** ```dotenv APP_URL=http://localhost:5173 BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### Python (FastAPI) · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **Environment variables on your server** ```dotenv APP_URL=https://your-app.com BLOCKAUTH_API_KEY=your_api_key BLOCKAUTH_API_SECRET= SESSION_SECRET= ``` #### .NET · development The public values go in `appsettings.json`. The secret never goes in a file you commit: in development use `user-secrets`, in production an environment variable. **appsettings.json** ```json { "APP_URL": "http://localhost:5173", "BLOCKAUTH_API_KEY": "your_api_key" } ``` **Terminal, in the project folder (development only)** ```bash dotnet user-secrets init dotnet user-secrets set "BLOCKAUTH_API_SECRET" "" ``` #### .NET · production Set them in your server or platform (Docker, your hosting…), not in a file you upload with your code. **appsettings.json** ```json { "APP_URL": "https://your-app.com", "BLOCKAUTH_API_KEY": "your_api_key" } ``` **Environment variable on your server (never in a repo file)** ```dotenv BLOCKAUTH_API_SECRET= ``` > **Placeholders in this code:** > > - Replace the API Secret placeholder with your API Secret, copied straight from the Dashboard. Never paste it on this site. > - Replace the SESSION\_SECRET placeholder with a random value generated on your computer: `openssl rand -hex 32`. > - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you. > - Replace `https://your-app.com` with your app URL, or fill in your data in the SDK Quickstart and it is filled in for you. Your frontend `apiKey` is baked in at build time: build with the production one. #### Vite (React · Vue) · development This is your frontend’s `.env`. The backend has its own file. **.env, next to the frontend package.json** ```dotenv VITE_BLOCKAUTH_API_KEY=your_api_key ``` #### Vite (React · Vue) · production It’s baked into the build, so it must exist where you build for production. Pick how you build: **File · .env.production · in your frontend folder** ```dotenv VITE_BLOCKAUTH_API_KEY=your_api_key ``` **Docker · Dockerfile · right before npm run build** ```dotenv ARG VITE_BLOCKAUTH_API_KEY RUN npm run build ``` **Docker · docker-compose.yml · in the service that builds your frontend** ```dotenv build: args: VITE_BLOCKAUTH_API_KEY: ${BLOCKAUTH_API_KEY} ``` **CI · Variable of your CI · in the job that runs npm run build** ```dotenv VITE_BLOCKAUTH_API_KEY=your_api_key ``` #### Next.js (React) · development This is your frontend’s `.env.local`. The backend has its own file. **.env.local, at the project root** ```dotenv NEXT_PUBLIC_BLOCKAUTH_API_KEY=your_api_key ``` #### Next.js (React) · production It’s baked into the build, so it must exist where you build for production. Pick how you build: **File · .env.production · in your frontend folder** ```dotenv NEXT_PUBLIC_BLOCKAUTH_API_KEY=your_api_key ``` **Docker · Dockerfile · right before npm run build** ```dotenv ARG NEXT_PUBLIC_BLOCKAUTH_API_KEY RUN npm run build ``` **Docker · docker-compose.yml · in the service that builds your frontend** ```dotenv build: args: NEXT_PUBLIC_BLOCKAUTH_API_KEY: ${BLOCKAUTH_API_KEY} ``` **CI · Variable of your CI · in the job that runs npm run build** ```dotenv NEXT_PUBLIC_BLOCKAUTH_API_KEY=your_api_key ``` #### Create React App (React) · development This is your frontend’s `.env`. The backend has its own file. **.env, at the project root** ```dotenv REACT_APP_BLOCKAUTH_API_KEY=your_api_key ``` #### Create React App (React) · production It’s baked into the build, so it must exist where you build for production. Pick how you build: **File · .env.production · in your frontend folder** ```dotenv REACT_APP_BLOCKAUTH_API_KEY=your_api_key ``` **Docker · Dockerfile · right before npm run build** ```dotenv ARG REACT_APP_BLOCKAUTH_API_KEY RUN npm run build ``` **Docker · docker-compose.yml · in the service that builds your frontend** ```dotenv build: args: REACT_APP_BLOCKAUTH_API_KEY: ${BLOCKAUTH_API_KEY} ``` **CI · Variable of your CI · in the job that runs npm run build** ```dotenv REACT_APP_BLOCKAUTH_API_KEY=your_api_key ``` #### Angular (environment.ts) · development Angular doesn’t use .env: your apiKey goes in this file. The backend variables go in their own file, your backend’s `.env`. **src/environments/environment.ts** ```typescript export const environment = { blockauthApiKey: 'your_api_key', } ``` #### Angular (environment.ts) · production Keep `environment.ts` with the development key and put the production one in `environment.prod.ts`, next to it. Then tell `angular.json` to swap them in the production build (`ng build`, the default configuration), so development keeps working on `localhost`. **src/environments/environment.prod.ts · new file** ```typescript export const environment = { blockauthApiKey: 'your_api_key', } ``` **angular.json · inside projects › your-app › architect › build › configurations › production** ```dotenv "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ] ``` #### apiKey written in the widget config (React · Vue · Angular) · development and production Your apiKey goes straight into the widget config (next step), no environment file. In the widget config, read the apiKey from that variable instead of writing `your_api_key`: - Vite (`src/main.jsx · src/main.ts`): `apiKey: import.meta.env.VITE_BLOCKAUTH_API_KEY,` - Next.js (`app/layout.tsx`): `apiKey: process.env.NEXT_PUBLIC_BLOCKAUTH_API_KEY,` - Create React App (`src/index.js`): `apiKey: process.env.REACT_APP_BLOCKAUTH_API_KEY,` - Angular (`src/app/app.config.ts`): `apiKey: environment.blockauthApiKey,` > **Placeholders in this code:** > > - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you. ### 3. Serve everything from your domain, over `https` There’s no dev proxy in production. Either your backend serves the frontend build, or your reverse proxy (Nginx, your load balancer) sends `/auth/blockauth` to your backend. Then make sure the session cookie is marked secure. The examples without the package already do it from `APP_URL`; with the package, it depends on your backend: **Only for Node.js:** - In your `session(...)`, add `secure: true` to `cookie`. - If a proxy terminates `https` in front of your backend, add `app.set('trust proxy', 1)`. Without it, Express doesn’t send the secure cookie and `/me` answers `401`. **Only for PHP:** - The package marks it secure when PHP sees `https`. If a proxy terminates `https` in front of PHP, pass it `HTTPS=on` (with Nginx and PHP-FPM, `fastcgi_param HTTPS on;`). **Only for Python (Flask):** - Add `SESSION_COOKIE_SECURE=True` to your Flask config. **Only for Python (FastAPI):** - Your `SessionMiddleware` has `https_only=True` (with `APP_URL` on `https`, the example above already does it). **Only for .NET:** - The package marks it secure over `https`. If a proxy terminates `https` in front of your app, add `app.UseForwardedHeaders()` with `ForwardedHeaders.XForwardedProto` before `UseAuthentication()`. ### 4. Allow the widget in your Content Security Policy If your server sends a `Content-Security-Policy` header (many frameworks, proxies and security templates add one), the browser blocks the widget until you allow it. You won't notice in development, because the frontend dev server doesn't send it: it shows up after deploying, with an unstyled button, a broken logo and a failing login. Check with `curl -sI https://your-domain | grep -i content-security-policy`; if it returns nothing, skip this step. Add these directives to the CSP you already send, keeping yours. If you already have one of them, add only the missing sources: **If you set `wsUrl`** (another Block-Auth server), write its host instead of `wss.block-auth.io` in `connect-src`, over `https` and `wss`. **Content-Security-Policy · HTTP header your server sends** ```text connect-src 'self' https://wss.block-auth.io wss://wss.block-auth.io; img-src 'self' data:; style-src 'self' 'unsafe-inline'; ``` - `connect-src`: the widget asks `wss.block-auth.io` for the login link, over `https` and `wss`; `'self'` covers your `authEndpoint`. - `img-src`: the Block-Auth logo in the button, embedded as a `data:` image. - `style-src`: the widget injects its styles in a `