Sign users in with FlowCatalyst
In this tutorial your web application stops managing passwords: people sign in on the platform’s hosted login page (password, passkey, a second factor, or their organisation’s SSO), and come back to your application signed in, with the roles they hold in your application. You will:
- declare a role for your application;
- provision a login client for it;
- give yourself the role;
- wire the login into your web application;
- sign in and read the user, roles and permissions.
It assumes the orders application from your first event, on a running
fcdev.
sequenceDiagram participant B as Browser participant App as Your web app participant FC as Platform (/oauth) B->>App: GET /dashboard (no session) App-->>B: 302 to FC /oauth/authorize (PKCE) B->>FC: sign in on the hosted page FC-->>B: 302 to App callback with a code B->>App: GET /callback?code=... App->>FC: exchange code (+ verifier) FC-->>App: id_token (roles for this app) + access token App-->>B: set the app's own session cookie, 302 /dashboard
Your application keeps its own session. The id_token is read once, at the callback: it lives for 5 minutes and says who signed in and which of your application’s roles they hold. The access token that comes with it is an identity token by default: it cannot call the platform API. See tokens for why.
1. Declare a role
Section titled “1. Declare a role”Roles belong to your application and are declared in code, with the permissions they grant. Add a
clerk role to the definitions you sync (the platform names it orders:clerk):
const definitions = sync .defineApplication("orders") .withRoles([{ name: "clerk", displayName: "Clerk", permissions: ["orders:sales:order:view", "orders:sales:order:create"] }]) .build();await client.definitions().sync(definitions);#[AsPermission(context: 'sales', aggregate: 'order', action: 'view', description: 'View orders')]final class ViewOrders {}
#[AsRole(name: 'clerk', displayName: 'Clerk', permissions: [ViewOrders::class])]final class ClerkRole {}Then php artisan flowcatalyst:scan && php artisan flowcatalyst:sync.
set := sync.ForApplication("orders"). AddRole(sync.MakeRole("clerk").WithDisplayName("Clerk"). WithPermissions("orders:sales:order:view", "orders:sales:order:create"))res := sync.NewSynchronizer(c).Sync(ctx, set, sync.DefaultOptions())var set = Definitions.DefinitionSet.define("orders") .withRoles(List.of(Definitions.Role.of("clerk").withPermissions(List.of( Definitions.Permission.of("sales", "order", "view"), Definitions.Permission.of("sales", "order", "create")))));client.definitions().sync(set);More on this in define and check permissions in code.
2. Provision a login client
Section titled “2. Provision a login client”A login client is an OAuth client with the authorization_code and refresh_token grants and the
openid profile email scopes, linked to your application, so the roles in its tokens are narrowed to
orders.
In the console, open Applications, then Orders, and under Login Client choose Provision
Login Client. Enter your application’s callback URL as the redirect URI, exactly (scheme, host and
port; localhost and 127.0.0.1 are different):
| Stack | Redirect URI in this tutorial |
|---|---|
| TypeScript (Fastify plugin) | http://localhost:3000/auth/callback |
| PHP (Laravel) | http://localhost:8000/flowcatalyst/callback |
| Go and Java (application framework) | http://localhost:3000/auth/callback |
Pick the client type:
- Confidential (has a secret) for a server-side web application. The TypeScript Fastify plugin needs one.
- Public (PKCE, no secret) for an application that cannot keep a secret. Laravel and the framework support both.
Copy the client id and, for a confidential client, the secret: it is shown once. The same operation
is POST /api/applications/{id}/provision-login-client with
{"clientType": "CONFIDENTIAL", "redirectUris": ["..."]}. Redirect URIs, allowed origins and secret rotation are managed afterwards
under OAuth clients.
3. Give yourself the role
Section titled “3. Give yourself the role”Open Users, then admin@flowcatalyst.local, and in the Roles section add orders:clerk.
A user with no roles and no permissions can sign in but reaches nothing on the platform except
their profile; your application would see an empty role list. The bootstrap administrator’s
platform:super-admin role is not one of orders’s roles, so without this step the id_token’s
roles for this client would be empty.
4. Wire the login
Section titled “4. Wire the login”The Fastify plugin runs the whole flow: /auth/login, /auth/callback, /auth/logout, an
encrypted session cookie, and Bearer-token checks for API callers.
pnpm add fastify @fastify/cookie joseimport Fastify from "fastify";import { flowcatalystAuth, defineRbac } from "@flowcatalyst/sdk/fastify";
// Roles arrive in the id_token; permissions are resolved locally from this catalogue.const rbac = defineRbac() .role("orders:clerk").grants("orders:sales:order:view", "orders:sales:order:create") .build();
const app = Fastify();await app.register(flowcatalystAuth, { baseUrl: "http://localhost:8080", clientId: process.env.FC_LOGIN_CLIENT_ID!, clientSecret: process.env.FC_LOGIN_CLIENT_SECRET!, cookie: { secret: process.env.SESSION_SECRET!, secure: false }, // secure: false only for http://localhost publicBaseUrl: "http://localhost:3000", rbac,});
app.get("/dashboard", { preHandler: app.fc.requireSession() }, async (req) => ({ id: req.principal!.id, roles: req.principal!.roles, canCreate: req.principal!.hasPermissionTo(["orders:sales:order:create"]),}));
await app.listen({ port: 3000 });Generate SESSION_SECRET once with
node -e "console.log(require('@flowcatalyst/sdk/fastify').generateSessionSecret())".
FLOWCATALYST_BASE_URL=http://localhost:8080FLOWCATALYST_OIDC_ENABLED=trueFLOWCATALYST_NATIVE_LOGIN=true # stock 'auth' middleware redirects guests into the loginFLOWCATALYST_OIDC_CLIENT_ID=<login client id>FLOWCATALYST_OIDC_CLIENT_SECRET=<secret> # omit for a public clientFLOWCATALYST_OIDC_SCOPE="openid profile email offline_access"Route::middleware('auth')->get('/dashboard', function () { $user = auth()->user(); return [ 'email' => $user->email, 'canView' => $user->can('orders:sales:order:view'), ];});The SDK registers /flowcatalyst/login, /callback, /logout and /refresh. With the
native-login bridge on, the default handler upserts a local user by email at sign-in and, if the
model uses spatie/laravel-permission’s HasRoles, mirrors the user’s roles and each role’s
permissions into Spatie’s tables, so can(), @can and policies work against a real record.
offline_access adds a refresh token, which POST /flowcatalyst/refresh uses to pick up role
changes.
In Go, use the application framework’s auth module (go/v0.2.1): it is the
relying party, keeps the session, and gives every route a context with the principal, client and
permissions.
web := httpfw.Declare(app)authd := auth.Declare(app, web)// in the build function:mod, err := authd.Build(ctx, b, auth.SessionStore(auth.MemoryStoreFactory()), // database or Redis stores for real use auth.Application(fw.MustApplicationCode("orders")), auth.Permissions(auth.ScopesMapper().And(auth.ByRole(map[string][]string{ "orders:clerk": {"orders:sales:order:view", "orders:sales:order:create"}, }))))srv, err := httpfw.NewServer(b, web, []*httpfw.Routes{mod.Routes(), mine}, httpfw.WithResolver(mod.Resolver()))Configuration: AUTH_ISSUER=http://localhost:8080, AUTH_CLIENT_ID, AUTH_CLIENT_SECRET
(confidential clients only) and AUTH_PUBLIC_BASE_URL=http://localhost:3000, with APP_ENV=local
to allow plain http. The module serves /auth/login, /auth/callback, /auth/session and
/auth/logout.
In Java, use the application framework’s AuthModule (framework-auth, v0.1.7):
App.builder() .module(new JettyHttpModule()) .module(new DatabaseModule()) .module(new AuthDatabaseModule()) // sessions in fw_session .module(AuthModule.builder() .application(new ApplicationCode("orders")) .permissions(PermissionMapper.scopes().and(PermissionMapper.byRole(Map.of( "orders:clerk", Set.of("orders:sales:order:view", "orders:sales:order:create"))))) .build()) .module(new OrdersModule()) .start();Configuration: AUTH_ISSUER=http://localhost:8080, AUTH_CLIENT_ID, AUTH_CLIENT_SECRET
(confidential clients only) and AUTH_PUBLIC_BASE_URL=http://localhost:3000, with APP_ENV=local
to allow plain http. Routes declared with RouteOptions.requiresContext() now require a
signed-in user or a valid bearer token.
5. Sign in
Section titled “5. Sign in”Open http://localhost:3000/dashboard (http://localhost:8000/dashboard for Laravel). You are sent
to the platform’s sign-in page, sign in as admin@flowcatalyst.local, and land back on the dashboard,
which shows your id, the role orders:clerk and the permission check.
What happened:
- Your application redirected to
/oauth/authorizewith PKCE (S256), astateand anonce. - After sign-in the platform redirected back with a one-time code, which your application exchanged for tokens and verified the id_token (signature, issuer, audience, expiry, nonce).
- The id_token’s
rolesheld only roles of applications the login client is linked to, so another application’s roles never reach yours. - Your application started its own session. From here on, the platform is not involved in each request; it is asked again only to refresh or when the session ends.
Where permissions come from
Section titled “Where permissions come from”The id_token carries roles. Mapping a role to permissions is your application’s own business,
and each stack does it locally: defineRbac() (TypeScript), Spatie’s tables filled at sign-in or a
bound RbacCatalogue (Laravel), ByRole / byRole (framework). Keep that map the same as the
roles you sync.
- Use FlowCatalyst as your app’s identity provider: sessions, logout, refresh, API routes, SSO and branded sign-in pages.
- Define and check permissions in code.
- Sign-in and federation and tokens.
- Build a customer portal, for your clients’ own customers.