SDK Quickstart

This guide will help you integrate Block-Auth authentication into any React application as simply and seamlessly as possible.


1. Installation

To install the SDK, add the updated library and SDK dependencies to your project by running:

# Using NPM
npm install @block-auth.io/blockauth-sdk-react @block-auth.io/blockauth-lib-react

# Using Yarn
yarn add @block-auth.io/blockauth-sdk-react @block-auth.io/blockauth-lib-react

2. Importing Components and Styles

To make the components work correctly from both a visual and logical perspective, it is strictly necessary to import the base styles. Block-Auth provides several components, but the two main ones you will need are FlowBlockAuth and DropdownProfile.

Add these lines to the main file where you will integrate the login (e.g., App.jsx):

// 1. Import the key components
import { FlowBlockAuth, DropdownProfile } from "@block-auth.io/blockauth-sdk-react";

// 2. Import the styles (CRITICAL for proper interface rendering)
import "@block-auth.io/blockauth-sdk-react/dist/main.css";

3. Implementing the Main Component

The FlowBlockAuth component is responsible for displaying the login interface and managing connections. You can pass it into your view using a configuration object with your credentials.

Here is a complete example of what your main authentication file (e.g., App.jsx or a dedicated Login.jsx view) should look like when everything is put together:

import React, { useState } from "react";
import {
  BlockAuthAppProvider,
  FlowBlockAuth,
  DropdownProfile
} from "@block-auth.io/blockauth-sdk-react";
import "@block-auth.io/blockauth-sdk-react/dist/main.css";

// Configure the variables obtained from your Dashboard
const config = {
  api_key: "YOUR_API_KEY",       // e.g., "app.65b0ee79..."
  api_secret: "YOUR_API_SECRET", // e.g., "052e56179eeda..."
  blockauth_provider: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
    },
    microsoft: {
      clientId: "YOUR_MICROSOFT_CLIENT_ID",
      tenantId: "common",
      authorityMode: "common",
    },
  },
};

export default function MyApp() {
  const [isLogged, setIsLogged] = useState(false);
  const locale = "en";

  // Callback to define custom logic when registration or login is successful
  const handleSuccess = async (address) => {
    console.log("Success! Authorized for address:", address);
    setIsLogged(true);
  };

  // Callback for errors
  const handleError = async () => {
    console.error("An error occurred during authentication.");
  };

  return (
    <BlockAuthAppProvider locale={locale} config={config.blockauth_provider}>
      <div className="app-container">
        {!isLogged ? (
          <FlowBlockAuth
            apiKey={config.api_key}
            apiSecret={config.api_secret}
            onSuccess={handleSuccess}
            onError={handleError}
          />
        ) : (
          <div>
            <h2>Session started successfully!</h2>
            <DropdownProfile
              apiKey={config.api_key}
              apiSecret={config.api_secret}
              onLogout={() => setIsLogged(false)}
            />
          </div>
        )}
      </div>
    </BlockAuthAppProvider>
  );
}

Understanding the code

  • 1) Configuration

    • Config Object (config): Centralizes SDK credentials (api_key, api_secret) and provider setup (blockauth_provider).
    • Provider Setup (BlockAuthAppProvider): Enables provider-specific SDK capabilities and is the recommended setup for most integrations.
    • Provider Scope: You can wrap the full app or only sections using Block-Auth components (FlowBlockAuth, DropdownProfile, or related UI). Both are valid; full-app wrapping is usually simpler for teams.
  • 2) Authentication and Session Flow

    • State Management (isLogged): Tracks whether the user has an active session.
    • Success Callback (handleSuccess): Triggered automatically by <FlowBlockAuth> after successful authentication, providing the user address/DID.
    • Conditional Rendering: Shows FlowBlockAuth when the user is not logged in, and shows the authenticated UI plus DropdownProfile after successful login.
  • 3) DropdownProfile Placement

    • You can place <DropdownProfile> anywhere in your UI (for example, a navbar or account menu) to manage the active session.
    • In this example, it is placed next to the login flow for clarity.
  • 4) Credentials and Ownership

    • config.api_key and config.api_secret are obtained during Link your application in Integration Quickstart.
    • config.blockauth_provider.google.clientId, config.blockauth_provider.microsoft.clientId, and config.blockauth_provider.microsoft.tenantId are managed by the BlockAuth team during the integration process.
    • Credentials are hardcoded here only to keep the example copy-paste friendly; in production, the integrator must define secure storage and handling.

4. Integrate with Your Existing Login System

Block-Auth is usually integrated as an additional authentication method. Most production apps need a bridge between the SDK callback and their own session model.

Recommended generic flow

  1. User authenticates with FlowBlockAuth.
  2. onSuccess returns the user identifier (address / DID).
  3. Frontend calls your backend login bridge endpoint.
  4. Backend maps or verifies the identity and returns your app session.
  5. Frontend stores your app session and continues the normal logged-in flow.

Minimal frontend contract

Your frontend should expect a backend response with at least:

{
  "token": "YOUR_APP_JWT_OR_SESSION_TOKEN",
  "role": "user",
  "full_name": "Jane Doe"
}

Coexistence with existing auth methods

Block-Auth can be your primary authentication experience, including in production-grade architectures. If your application already has password, OTP, or SSO flows, you can integrate Block-Auth as an additional sign-in option during migration or hybrid rollout phases.


5. Production Connectivity and CSP Setup

This section is intentionally framework-agnostic for frontend architecture and applies to any React app (Vite, CRA, Next.js, etc.). If Block-Auth runs in the browser, your frontend host must allow the SDK network targets through CSP.

Why this is necessary

  • Browser-enforced CSP: Even with correct frontend code, the browser blocks requests to non-allowed domains.
  • SDK transport requirements: Block-Auth needs outbound API and WebSocket connectivity.
  • Deployment consistency: Explicit CSP rules reduce environment-only failures in staging and production.

Universal implementation for React apps

Use the same FlowBlockAuth integration shown in section 3. Implementing the Main Component, and set wsUrl according to your deployment endpoint.

Apply this CSP configuration on the server/gateway that returns your frontend (Express, Nginx, or equivalent):

  • Express apps: add it in your server bootstrap file (commonly server.js, app.js, or backend/index.js) in the middleware section, before serving frontend assets/routes.
  • Nginx deployments: define the equivalent CSP header in your site/server config (nginx.conf or virtual host file) for the frontend responses.
const cspConnectSrc = [
  "'self'",
  "https://api.block-auth.io",
  "wss://wss.block-auth.io",
  "wss://your-ws-endpoint.example.com",
  "https://accounts.google.com",
  "https://login.microsoftonline.com",
  "https://graph.microsoft.com",
  "https://*.msauth.net",
];

const cspScriptSrc = [
  "'self'",
  "'unsafe-inline'",
  "https://accounts.google.com",
  "https://apis.google.com",
  "https://www.gstatic.com",
  "https://*.gstatic.com",
  "https://login.microsoftonline.com",
];

const cspImgSrc = [
  "'self'",
  "data:",
  "blob:",
  "https:",
];

const cspFrameSrc = [
  "'self'",
  "https://accounts.google.com",
  "https://login.microsoftonline.com",
  "https://*.microsoftonline.com",
  "https://*.block-auth.io",
];

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        connectSrc: cspConnectSrc,
        scriptSrc: cspScriptSrc,
        imgSrc: cspImgSrc,
        frameSrc: cspFrameSrc,
      },
    },
  })
);

Note: It does not matter whether your CSP is configured in Express, Nginx, or another gateway. What matters is the final CSP header received by the browser.


6. Security Checklist

Use this checklist before going live:

  • Do not hardcode production credentials in source code. Prefer your frontend bundler environment variables.
  • Restrict API key and secret usage, and rotate credentials regularly.
  • Validate and sanitize the identity value (address / DID) before creating local sessions.
  • Protect your backend bridge endpoint with rate limiting and logging.
  • Store session tokens securely and follow your platform session hardening practices.

7. Customization Options (Props)

FlowBlockAuth is highly customizable. The list below reflects the current SDK behavior.

Credentials and Callbacks

  • apiKey (string): API key.
  • apiSecret (string): API secret.
  • onSuccess (function): Asynchronous callback executed after a successful login.
  • onError (function): Asynchronous callback executed when an error occurs.
  • onLogout (function): Asynchronous callback executed when logging out.
  • wsUrl (string): Define the WebSockets URL.

Behavior and Interface

  • showDropdownWhenConnected (boolean): Shows the profile dropdown when an active session is detected (default: true).
  • isInsideModal (boolean): Set to true when rendering inside a custom modal container (default: false).
  • containerRef (ref): Container reference used with isInsideModal for click-outside behavior.
  • btnSize (string): Button size (default: "small"; values: "xxs", "xs", "tiny", "small", "base", "large").

Localization

  • Language is controlled through BlockAuthAppProvider using locale, not through a FlowBlockAuth language prop.
  • Available values are currently es and en.

Advanced Styling

  • btnClassNames
  • btnTextClassNames
  • _btnBgClassNames
  • _btnPaddingClassNames
  • btnLoaderColor
  • dropdownBtnSize
  • dropdownBtnBgClassNames
  • dropdownBtnTextColorClassNames
  • dropdownBtnBorderClassNames
  • dropdownHeight
  • additionalDropdownItems (array): To add other options to the user's dropdown menu.

Was this page helpful?