widget_chat is live on pub.dev: drop-in AI chat for Flutter, FlutterFlow, iOS, Android, React & Web. Start free →

← Back to Blog
Flutter Chat Identity Verification with HMAC

Flutter Chat Identity Verification with HMAC

fluttersecurityhmacchatbotflutterflow

Your Flutter app has logins. Your support bot can look up orders, past tickets and account details. Then someone opens the app, changes one string, and the bot starts reading them a stranger's order history.

That is the hole identity verification closes. Intercom, Zendesk and others document it for web, iOS and Android, but a Flutter developer usually has to stitch it together from those pages. This post does it end to end for a Flutter or FlutterFlow app: the spoofing risk, the backend endpoint, the Dart side, refreshing on user change, and a rollout that does not lock out users on old builds.

If you would rather not run the chat backend at all, the widget_chat package already supports a signed user ID. It is covered at the end. The pattern below works for any chat that trusts a user ID.

The problem: any client can send any userID

A chat widget in a logged-in app normally sends something like this with each message:

{ "user_id": "user-123", "message": "Where is my order?" }

The server uses user_id to load history and to scope tools such as "get my orders". But the app runs on a device you do not control. A user can patch the binary, run it through a proxy like mitmproxy, or replay the request with curl. Anything the client sends is a claim, and nothing proves it.

Your project key does not help either. It ships inside the app bundle, so anyone who unzips the APK or IPA has it. A public key plus a guessable user ID (sequential integers, emails, Firebase UIDs leaked in a screenshot) is enough to read someone else's chat.

Unsigned userID

  • The client says who the user is
  • Change user-123 to user-124 and the bot believes it
  • History and order tools answer for the wrong person
  • The project key in the bundle does not stop it

Signed userID

  • The client sends the ID plus an HMAC from your backend
  • The chat server recomputes the HMAC and rejects a mismatch
  • Changing the ID breaks the signature
  • The signing secret never leaves your servers
The ID stays public. What changes is that only your backend can vouch for it.

How HMAC signing fixes it

HMAC-SHA256 takes a secret key and a message and returns a 64 character hex digest. Without the key you cannot produce a valid digest for a new message, and you cannot work the key out from digests you have seen.

So the scheme is:

  1. Your backend and the chat server share one secret.
  2. After login, your backend computes HMAC-SHA256(secret, userId) and hands it to the app.
  3. The app passes the user ID and the signature to the chat.
  4. The chat server recomputes the HMAC for that user ID and compares. No match, no history, no tools.
User logs inApp gets session tokenApp calls POST /chat/identity
Your backend verifies the sessionBackend signs the user ID with HMAC-SHA256Returns the signature
App opens chat with userID + signatureChat server recomputes HMACMatch: serve history and tools
Mismatch or missingReject the request

This is the same model Intercom uses for its user_hash: the hash is computed on your server, keyed with a secret, over the user ID, and the client must send the identifier it hashed alongside it. Intercom now recommends JWTs for new setups, but HMAC over the user ID remains the common pattern across chat vendors and it is what this post builds.

Here is what the digest looks like for a worked example with the secret demo-secret:

userID HMAC-SHA256 hex
user-123 1605f96d62722a6ff8b43981676657601b6549c31c1a14ed921c3ed7f12f7afe
user-124 8de57b1258c68d7f21c22ea60d71c79ca6edfaa3fd9d6654a080ff42ad7810cb

One character changed in the ID, a completely different signature. Use these as test vectors when you wire up your own endpoint.

Step 1: the backend signing endpoint

The one rule that matters: the user ID you sign comes from the verified session, never from the request body. If the endpoint signs whatever ID the client asks for, you have built a signature vending machine and fixed nothing.

Here is a Node.js endpoint for an app on Firebase Auth. It verifies the Firebase ID token with the Admin SDK, takes the UID from the decoded token, and signs it with Node's built-in crypto module:

import express from 'express';
import { createHmac } from 'node:crypto';
import { initializeApp } from 'firebase-admin/app';
import { getAuth } from 'firebase-admin/auth';

initializeApp();
const app = express();
const IDENTITY_SECRET = process.env.CHAT_IDENTITY_SECRET; // from your secret manager

app.post('/chat/identity', async (req, res) => {
  const header = req.get('Authorization') ?? '';
  const idToken = header.startsWith('Bearer ') ? header.slice(7) : null;
  if (!idToken) return res.status(401).end();

  try {
    const { uid } = await getAuth().verifyIdToken(idToken);
    const signature = createHmac('sha256', IDENTITY_SECRET)
      .update(uid)
      .digest('hex');
    res.json({ userId: uid, signature });
  } catch {
    res.status(401).end();
  }
});

app.listen(8080);

The same thing in Python, if your backend is Django or FastAPI:

import hmac, hashlib

def sign_user_id(user_id: str, secret: str) -> str:
    return hmac.new(secret.encode(), user_id.encode(), hashlib.sha256).hexdigest()

Returning userId along with the signature matters. The app should use the ID the server signed, not one it computed locally, so the two can never drift apart.

Step 2: fetch the signature in Dart after login

On the app side, fetch the signature once the user is signed in. This uses package:http and firebase_auth; swap in your own auth client if you use something else.

import 'dart:convert';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:http/http.dart' as http;

class ChatIdentity {
  const ChatIdentity(this.userId, this.signature);
  final String userId;
  final String signature;
}

Future<ChatIdentity?> fetchChatIdentity(User user) async {
  final idToken = await user.getIdToken();
  final res = await http.post(
    Uri.parse('https://api.example.com/chat/identity'),
    headers: {'Authorization': 'Bearer $idToken'},
  );
  if (res.statusCode != 200) return null;
  final body = jsonDecode(res.body) as Map<String, dynamic>;
  return ChatIdentity(body['userId'] as String, body['signature'] as String);
}

Step 3: refresh it when the user changes

A signature belongs to one user ID. If someone logs out and a second person logs in on the same device, the chat must not keep the first user's identity, or the first user's signature, around. Tie the identity to the auth stream so it is rebuilt every time the user changes:

final chatIdentityProvider = StreamProvider<ChatIdentity?>((ref) {
  return FirebaseAuth.instance.authStateChanges().asyncMap(
        (user) => user == null ? null : fetchChatIdentity(user),
      );
});

That is a Riverpod StreamProvider, but a StreamBuilder on authStateChanges() does the same job. A few rules that come out of this:

  • Do not persist the signature to disk. Fetch it per session; it is one cheap request.
  • Give the chat widget a key derived from the user ID, so Flutter builds a fresh chat when the user switches instead of reusing state.
  • If the fetch fails, show the chat for anonymous users or not at all. Do not fall back to an unsigned logged-in ID.
  • If you rotate the secret, old signatures stop matching. Because the app refetches on each login, rotating plus a forced re-login is enough.

Step 4: roll out the client before enforcing

Turning verification on before your users have the new build breaks chat for everyone on an old version, because their requests carry no signature. Do it in this order:

  1. Deploy the signing endpointShip POST /chat/identity and test it against the vectors above.
  2. Release the app updateThe new build fetches the signature and sends it, while the server still accepts unsigned requests.
  3. Watch adoptionWait until the share of chat traffic without a signature is low enough, or until you raise the minimum supported version.
  4. Turn on enforcementThe chat server now rejects any request whose signature is missing or wrong.
  5. Test the attackChange the user ID in a debug build and confirm the bot refuses it.

On the web build of your Flutter app the new code is live on the next page load, so this mostly matters for the store builds.

FlutterFlow notes

In FlutterFlow, put the /chat/identity call in an API call or custom action that runs after login, store the result in page or app state for the session, and pass it into the custom widget that hosts the chat. The secret stays on your backend (Cloud Functions, Supabase Edge Functions or your own server), never in a FlutterFlow constant.

Doing it with widget_chat

Everything above assumes you run the chat backend yourself and also write the server-side check. Widget-Chat is the version where you only do step 1 and 2. The widget_chat package ships the finished chat screen for Flutter and FlutterFlow, and its configuration already takes an HMAC-SHA256 signature of the user ID:

ChatWidget(
  key: ValueKey(identity.userId),
  configuration: BotConfiguration(
    projectSecretKey: 'your-project-secret-key',
    userID: identity.userId,
    userIdSignature: identity.signature,
  ),
)

userIdSignature is the hex digest of userID keyed by your project's identity secret, computed on your backend exactly like the endpoint above. Widget-Chat verifies it server-side before serving that user's chat. The field is optional so existing installs keep working, and once you turn on required verification for the project in the dashboard, a request without a valid signature is refused. That gives you the same client-first rollout described above.

Install it with flutter pub add widget_chat, and create a free project to get your project key. No credit card.

  • The signed user ID comes from a verified session, never from the request body
  • The identity secret lives only on the server
  • The app fetches the signature after login and drops it on logout
  • The chat is rebuilt when the user changes
  • The client ships before enforcement is turned on

The widget_chat package on pub.dev

Dart's crypto package, which can compute HMAC, and why the secret must not ship with it

Add an AI chat to your Flutter app without building it

Widget-Chat is a drop-in chat widget for Flutter and FlutterFlow. Add the package, pass your project key, and the whole chat screen is there. You set up the assistant in a no-code dashboard.

flutter pub add widget_chat

Free plan, no credit card.

Widget-Chat

About the author

Widget-Chat is built by a small team of Flutter developers. We write about the problems we hit while shipping AI chat in production apps.