- Updated: March 22, 2026
- 9 min read
Adding User Authentication and Management to the OpenClaw Full‑Stack Template
To add user authentication and management to the OpenClaw full‑stack template, select an authentication provider (Auth0, Supabase, or a self‑hosted OIDC server), configure the provider, inject auth middleware into the OpenClaw gateway, adapt the memory layers to carry user context, and finally redeploy the secured stack on UBOS.
1. Introduction
OpenClaw is a powerful full‑stack starter kit that combines a GraphQL gateway, a flexible memory layer, and a set of ready‑to‑use UI components. While the default template ships without authentication, most production workloads require robust user management. This guide walks developers and DevOps engineers through the end‑to‑end process of securing OpenClaw, from provider selection to a production‑ready deployment on the UBOS platform overview. By the end of the article you will have a fully‑functional, auth‑protected OpenClaw instance that can be scaled, monitored, and extended with UBOS’s AI‑enhanced tooling.
2. Choosing an Authentication Provider
Choosing the right provider hinges on three factors: security compliance, developer experience, and cost. Below is a MECE breakdown of the three most common options.
Auth0
Auth0 offers a fully‑managed Identity‑as‑a‑Service platform with built‑in social logins, MFA, and extensive rule‑engine capabilities. Ideal for enterprises that need quick time‑to‑market without managing infrastructure.
- Supports OIDC, SAML, and OAuth2.
- Rich dashboard for user analytics.
- Free tier for up to 7,000 active users.
Supabase
Supabase provides an open‑source Firebase alternative with built‑in Postgres, real‑time subscriptions, and a simple auth module. It’s perfect for startups that want a low‑cost, self‑hostable solution.
- OIDC‑compatible JWTs.
- Native email/password and third‑party OAuth.
- Free tier includes 500 MB storage.
Self‑hosted OIDC
Running your own OIDC server (e.g., Keycloak, FusionAuth) gives you full control over data residency, custom claims, and compliance requirements such as GDPR or HIPAA.
- Zero vendor lock‑in.
- Customizable authentication flows.
- Requires operational overhead.
For the purpose of this tutorial we’ll demonstrate the integration steps for each provider, allowing you to pick the one that best matches your project constraints.
3. Configuring the Selected Provider
3.1 Registering the Application
All three providers require you to register a new “application” (sometimes called a client). This step generates a client_id and client_secret that OpenClaw will use to validate tokens.
- Auth0: Navigate to Applications → Create Application → Regular Web App. Record the Domain, Client ID, and Client Secret.
- Supabase: In the Supabase dashboard, go to Authentication → Settings → URL Configuration. Enable “External OAuth Providers” and copy the
anon keyandservice_role key. - Self‑hosted OIDC (Keycloak example): Create a new client under Clients → Create. Set
Access Typetoconfidentialand note the generated credentials.
3.2 Setting Callbacks and Scopes
OpenClaw’s gateway expects the authentication flow to redirect back to https://<your‑domain>/auth/callback. Add this URL to the provider’s “Allowed Callback URLs” list. Additionally, request the openid, profile, and email scopes to obtain user identity information.
// Example Auth0 callback configuration
{
"allowed_callbacks": [
"https://my-openclaw-app.com/auth/callback"
],
"allowed_logout_urls": [
"https://my-openclaw-app.com"
],
"grant_types": ["authorization_code", "refresh_token"],
"scopes": ["openid", "profile", "email"]
}
For Supabase, the same settings are found under Authentication → Settings → Redirect URLs. For a self‑hosted OIDC server, edit the client’s redirect_uris in the admin console.
4. Updating OpenClaw Gateway
The gateway is the entry point for all GraphQL requests. Adding authentication involves two steps: inserting a middleware that validates JWTs and protecting individual resolvers.
4.1 Adding Auth Middleware
OpenClaw uses express under the hood. Create a new file src/middleware/auth.js and paste the following snippet. The example uses the express-jwt library, which works with any OIDC‑compatible token.
// src/middleware/auth.js
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
function authMiddleware(options) {
return jwt({
// Dynamically provide a signing key based on the kid in the header and the JWKS endpoint.
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: options.jwksUri, // e.g., https://YOUR_DOMAIN/.well-known/jwks.json
}),
audience: options.audience,
issuer: options.issuer,
algorithms: ['RS256'],
});
}
module.exports = authMiddleware;
In src/server.js import and apply the middleware before the GraphQL endpoint:
// src/server.js
const express = require('express');
const authMiddleware = require('./middleware/auth');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema');
const app = express();
// Load provider‑specific config from environment variables
const authConfig = {
jwksUri: process.env.AUTH_JWKS_URI,
audience: process.env.AUTH_AUDIENCE,
issuer: process.env.AUTH_ISSUER,
};
app.use('/auth', authMiddleware(authConfig));
// GraphQL endpoint (protected)
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true,
customFormatErrorFn: (err) => ({
message: err.message,
code: err.originalError && err.originalError.code,
}),
}));
app.listen(process.env.PORT || 4000, () => console.log('OpenClaw gateway running'));
Notice how the middleware is attached to the /auth path. All subsequent routes, including /graphql, inherit the validated req.user object.
4.2 Protecting Routes
Not every GraphQL query needs authentication (e.g., public product listings). Use resolver‑level guards to enforce security where needed.
// src/resolvers/userResolver.js
module.exports = {
Query: {
me: (parent, args, context) => {
if (!context.user) {
throw new Error('Authentication required');
}
return context.user; // Returns JWT payload
},
// Example of a public resolver
publicProducts: async () => {
return await getProducts(); // No auth check
},
},
};
When initializing the GraphQL server, pass the user from the request into the context:
// src/server.js (add after auth middleware)
app.use('/graphql', (req, res, next) => {
req.context = { user: req.user };
next();
});
With these changes, any resolver that accesses context.user will automatically enforce authentication.
5. Modifying Memory Layers for User Context
The memory layer in OpenClaw stores transient data such as session state, caching, and user‑specific preferences. To make it auth‑aware, you need to embed the user identifier into the key schema and adjust the access logic.
5.1 Storing User Sessions
Assume you are using Redis as the backing store (the default in UBOS). Extend the session helper to prefix keys with the user’s sub claim.
// src/memory/session.js
const redis = require('redis');
const client = redis.createClient({ url: process.env.REDIS_URL });
function getSessionKey(userId) {
return `session:${userId}`;
}
async function setUserSession(userId, data) {
const key = getSessionKey(userId);
await client.set(key, JSON.stringify(data), 'EX', 3600); // 1‑hour TTL
}
async function getUserSession(userId) {
const key = getSessionKey(userId);
const raw = await client.get(key);
return raw ? JSON.parse(raw) : null;
}
module.exports = { setUserSession, getUserSession };
In your resolver, you can now read/write session data based on the authenticated user:
// src/resolvers/sessionResolver.js
const { setUserSession, getUserSession } = require('../memory/session');
module.exports = {
Mutation: {
updatePreferences: async (_, { input }, { user }) => {
if (!user) throw new Error('Authentication required');
await setUserSession(user.sub, { preferences: input });
return true;
},
},
Query: {
myPreferences: async (_, __, { user }) => {
if (!user) throw new Error('Authentication required');
const session = await getUserSession(user.sub);
return session ? session.preferences : {};
},
},
};
5.2 Access Control in Memory Services
Beyond sessions, you may have domain‑specific caches (e.g., product recommendations). Apply a similar key‑prefix strategy and enforce role‑based checks if your JWT includes a role claim.
// src/memory/cache.js
function getCacheKey(userId, resource) {
return `cache:${userId}:${resource}`;
}
// Example: only admins can clear the global cache
async function clearCache(user) {
if (user.role !== 'admin') {
throw new Error('Insufficient permissions');
}
await client.flushdb();
}
These patterns keep user data isolated, prevent cross‑tenant leakage, and align with best practices for multi‑tenant SaaS applications.
6. Deploying the Secured Stack on UBOS
UBOS simplifies the deployment of full‑stack applications through declarative manifests. After you have hardened OpenClaw, the next step is to push the changes to UBOS, configure secrets, and verify the deployment.
6.1 Updating UBOS Manifests
Open the ubos.yaml file located at the root of your repository. Add a new service definition for the gateway if it isn’t already present, and inject the environment variables required for authentication.
# ubos.yaml
services:
openclaw-gateway:
image: ghcr.io/ubos/openclaw-gateway:latest
ports:
- "4000:4000"
env:
- AUTH_JWKS_URI=${{ secrets.AUTH_JWKS_URI }}
- AUTH_AUDIENCE=${{ secrets.AUTH_AUDIENCE }}
- AUTH_ISSUER=${{ secrets.AUTH_ISSUER }}
- REDIS_URL=${{ secrets.REDIS_URL }}
depends_on:
- redis
redis:
image: redis:6-alpine
ports:
- "6379:6379"
Notice the ${{ secrets.* }} syntax – UBOS will pull these values from the secure secret store, keeping credentials out of source control.
6.2 Environment Variables for Secrets
Navigate to the UBOS partner program dashboard and create the following secrets:
- AUTH_JWKS_URI – JWKS endpoint of your provider (e.g.,
https://my-auth0-domain/.well-known/jwks.json). - AUTH_AUDIENCE – The API identifier you set in the provider.
- AUTH_ISSUER – Issuer URL (e.g.,
https://my-auth0-domain/). - REDIS_URL – Connection string for the Redis instance (UBOS provides a managed Redis service).
UBOS also supports secret rotation via its Workflow automation studio, allowing you to schedule automatic key refreshes without downtime.
6.3 Deploying the Application
Commit your changes and push to the repository linked with UBOS. Then trigger a deployment from the UBOS UI or run the CLI command:
# Deploy via UBOS CLI
ubos deploy --manifest ubos.yaml --env production
UBOS will build the Docker images, inject the secrets, and spin up the services. You can monitor the rollout in real time on the Enterprise AI platform by UBOS dashboard.
6.4 Testing the Deployment
After the stack is live, perform the following checks:
- Visit
https://your-domain.com/auth/callbackand ensure you are redirected to the provider’s login page. - Log in with a test user and verify that the JWT is stored in a secure HttpOnly cookie.
- Run a GraphQL query against
/graphqlthat requires authentication (e.g.,{ me { sub email } }) and confirm the response contains user data. - Attempt the same query without a token and verify you receive an “Authentication required” error.
If any step fails, review the UBOS logs (ubos logs openclaw-gateway) and the provider’s dashboard for mis‑configured callback URLs or scopes.
7. Conclusion and Next Steps
By following this guide you have transformed the OpenClaw full‑stack template from an open, unauthenticated demo into a production‑grade, user‑centric application. The key takeaways are:
- Select the auth provider that aligns with your security, cost, and operational goals.
- Configure callbacks, scopes, and secrets precisely to avoid token validation errors.
- Inject middleware at the gateway level and guard resolvers for fine‑grained access control.
- Make the memory layer user‑aware to keep session data isolated per identity.
- Leverage UBOS’s declarative manifests, secret management, and monitoring tools for a seamless, repeatable deployment.
Ready to accelerate your AI‑powered workflows? Explore the AI marketing agents that can auto‑generate copy, or try the UBOS templates for quick start to spin up new micro‑services in minutes.
For a deeper dive into AI‑enhanced development, check out the AI SEO Analyzer or the AI Article Copywriter. Both tools integrate seamlessly with the same authentication flow you just built, ensuring your content pipelines stay secure.
Happy coding, and enjoy the security and scalability that UBOS brings to your OpenClaw projects!
Source: Original news article on OpenClaw authentication
Andrii Bidochko
CTO UBOS
Andrii Bidochko is an AI entrepreneur and researcher focused on AI agents, reinforcement learning, and autonomous systems. He writes about the technologies shaping the future of machine intelligence, from frontier models and agent architectures to real-world AI applications.