Sign in through the hosted page
Send the browser to your organization's sign-in page and come back with tokens. The app never sees a password.
What it shows
- The app creates a PKCE verifier and sends the browser to the authorization endpoint.
- The person signs in on the hosted page, with the methods that the organization turned on.
- The callback address of the app exchanges the code for tokens and reads the profile.
- The app asks the SDK for the access token and calls an API with it. The SDK renews the token before it expires.
- Sign-out removes the tokens and ends the session at LumoAuth.
The React version uses the components of @lumoauth/react. The Vue and Angular versions use AuthModule and LumoAuthSession from @lumoauth/client, which do the same work without components.
Before you start
You need an application for a browser app: a public client with a redirect URI and an allowed origin.
A new organization has one, the Starter App. Open Applications in the portal and copy its client ID. It accepts http://localhost:5173 and http://localhost:3000, the two addresses that this recipe uses.
For an application of your own:
- Open Applications and click New application.
- Enter an Application name and choose Single-page or mobile app.
- Enter the Redirect URI, for example
http://localhost:5173/auth/callback, and click Create application. - Open the Configuration tab of the application. Under Browser CORS origins, enter the origin of your app in Allowed origins, for example
http://localhost:5173. - Click Save configuration.
Without step 4 the browser blocks the token request right after sign-in.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_CLIENT_ID | The client ID of the application. A browser app has no client secret. |
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. Each version is a small project with its own package.json. A real browser signed in through each one, called UserInfo, renewed the token and signed out.
- React
- Vue
- Angular
// Sign in through the hosted page of your organization, with React.
//
// cd sign-in/hosted-page/js/react && npm install && npm run dev
//
// Then open http://localhost:5173.
import { createRoot } from 'react-dom/client';
import { AuthCallback, LumoAuthProvider } from '@lumoauth/react';
import App from './App.jsx';
// The hosted page sends the browser back to this address with a code.
const callbackPath = '/auth/callback';
createRoot(document.getElementById('root')).render(
<LumoAuthProvider
domain={import.meta.env.LUMOAUTH_URL}
orgId={import.meta.env.LUMOAUTH_ORG_ID}
clientId={import.meta.env.LUMOAUTH_CLIENT_ID}
redirectUri={window.location.origin + callbackPath}
>
{/* AuthCallback exchanges the code for tokens, then opens the start page. */}
{window.location.pathname === callbackPath ? <AuthCallback afterSignInUrl="/" /> : <App />}
</LumoAuthProvider>,
);
// The start page: a sign-in button, or the profile of the signed-in person.
import { useState } from 'react';
import { SignedIn, SignedOut, SignInButton, SignOutButton, useLumoAuth, useSession, useUser } from '@lumoauth/react';
export default function App() {
return (
<main>
<h1>Sign in through the hosted page</h1>
<SignedOut>
<p>Nobody is signed in.</p>
{/* Creates the PKCE verifier and sends the browser to the hosted page. */}
<SignInButton />
</SignedOut>
<SignedIn>
<Profile />
<SignOutButton />
</SignedIn>
</main>
);
}
function Profile() {
const user = useUser();
const { getToken } = useSession();
const client = useLumoAuth();
const [answer, setAnswer] = useState('');
// getToken() returns the access token and renews it first when it is about
// to expire. Send it to your own API in the same way.
async function callApi() {
const token = await getToken();
const info = await client.auth.getUserInfo(token);
setAnswer(`UserInfo with the access token: sub ${info.sub}`);
}
if (!user) return <p>Loading the profile…</p>;
return (
<>
<p>Signed in as {user.email}</p>
<p>Name: {user.displayName}</p>
<button type="button" onClick={callApi}>Call the API</button>
<p>{answer}</p>
</>
);
}
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// The browser gets these three values and nothing else from the environment.
// None of them is a secret: a browser app has no client secret and no API key.
export default defineConfig({
plugins: [react()],
define: {
'import.meta.env.LUMOAUTH_URL': JSON.stringify(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev'),
'import.meta.env.LUMOAUTH_ORG_ID': JSON.stringify(process.env.LUMOAUTH_ORG_ID ?? ''),
'import.meta.env.LUMOAUTH_CLIENT_ID': JSON.stringify(process.env.LUMOAUTH_CLIENT_ID ?? ''),
},
});
cd sign-in/hosted-page/js/react && npm install && npm run dev
Open http://localhost:5173.
// Sign-in, the callback, the tokens and sign-out, with @lumoauth/client.
import { AuthModule, LumoAuthSession } from '@lumoauth/client';
// The hosted page sends the browser back to this address with a code.
export const callbackPath = '/auth/callback';
const redirectUri = window.location.origin + callbackPath;
export const auth = new AuthModule({
baseUrl: import.meta.env.LUMOAUTH_URL,
orgId: import.meta.env.LUMOAUTH_ORG_ID,
clientId: import.meta.env.LUMOAUTH_CLIENT_ID,
});
// The session keeps the tokens in sessionStorage. Its getToken() renews the
// access token first when it is about to expire.
export const session = new LumoAuthSession({ auth, redirectUri });
// Creates the PKCE verifier and sends the browser to the hosted page.
export async function signIn() {
const { url, codeVerifier, state } = await session.buildAuthorizationUrl();
sessionStorage.setItem('pkce', JSON.stringify({ codeVerifier, state }));
window.location.href = url;
}
// On the callback address: exchanges the code for tokens.
export async function finishSignIn() {
const params = new URLSearchParams(window.location.search);
const saved = JSON.parse(sessionStorage.getItem('pkce') ?? '{}');
sessionStorage.removeItem('pkce');
if (params.get('error')) throw new Error(params.get('error_description') ?? params.get('error'));
// The state must be the value that this browser sent.
if (!params.get('code') || !saved.state || params.get('state') !== saved.state) {
throw new Error('The callback does not belong to a sign-in that this browser started.');
}
const tokens = await auth.exchangeCodeForTokens({
code: params.get('code'),
codeVerifier: saved.codeVerifier,
redirectUri,
});
await session.adopt(tokens);
}
// Removes the tokens, then ends the session at LumoAuth as well.
export async function signOut() {
const { idToken } = session.getTokens();
await session.clearSession();
window.location.href = auth.buildEndSessionUrl({
idTokenHint: idToken ?? undefined,
postLogoutRedirectUri: window.location.origin + '/',
});
}
<!-- The start page: a sign-in button, or the profile of the signed-in person. -->
<script setup>
import { onMounted, ref } from 'vue';
import { auth, callbackPath, finishSignIn, session, signIn, signOut } from './auth.js';
const status = ref('loading');
const user = ref(null);
const answer = ref('');
const error = ref('');
onMounted(async () => {
try {
if (window.location.pathname === callbackPath) {
await finishSignIn();
window.history.replaceState({}, '', '/');
}
// Reads the tokens that an earlier page load stored.
await session.hydrate();
if (session.getSnapshot().isSignedIn) {
user.value = await auth.getUserInfo(await session.getToken());
}
} catch (reason) {
error.value = reason.message;
}
status.value = session.getSnapshot().status;
});
// getToken() returns the access token and renews it first when it is about
// to expire. Send it to your own API in the same way.
async function callApi() {
const token = await session.getToken();
const info = await auth.getUserInfo(token);
answer.value = `UserInfo with the access token: sub ${info.sub}`;
}
</script>
<template>
<main>
<h1>Sign in through the hosted page</h1>
<p v-if="error" role="alert">Sign-in did not finish: {{ error }}</p>
<template v-if="status === 'unauthenticated'">
<p>Nobody is signed in.</p>
<button type="button" @click="signIn">Sign in</button>
</template>
<template v-if="status === 'authenticated' && user">
<p>Signed in as {{ user.email }}</p>
<p>Name: {{ user.name }}</p>
<button type="button" @click="callApi">Call the API</button>
<p>{{ answer }}</p>
<button type="button" @click="signOut">Sign out</button>
</template>
</main>
</template>
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
// The browser gets these three values and nothing else from the environment.
// None of them is a secret: a browser app has no client secret and no API key.
export default defineConfig({
plugins: [vue()],
define: {
'import.meta.env.LUMOAUTH_URL': JSON.stringify(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev'),
'import.meta.env.LUMOAUTH_ORG_ID': JSON.stringify(process.env.LUMOAUTH_ORG_ID ?? ''),
'import.meta.env.LUMOAUTH_CLIENT_ID': JSON.stringify(process.env.LUMOAUTH_CLIENT_ID ?? ''),
},
});
cd sign-in/hosted-page/js/vue && npm install && npm run dev
Open http://localhost:5173.
// Sign-in, the callback, the tokens and sign-out, with @lumoauth/client.
import { AuthModule, LumoAuthSession } from '@lumoauth/client';
// The start script passes these three values from the environment.
// None of them is a secret: a browser app has no client secret and no API key.
declare const LUMOAUTH_URL: string;
declare const LUMOAUTH_ORG_ID: string;
declare const LUMOAUTH_CLIENT_ID: string;
// The hosted page sends the browser back to this address with a code.
export const callbackPath = '/auth/callback';
const redirectUri = window.location.origin + callbackPath;
export const auth = new AuthModule({
baseUrl: LUMOAUTH_URL,
orgId: LUMOAUTH_ORG_ID,
clientId: LUMOAUTH_CLIENT_ID,
});
// The session keeps the tokens in sessionStorage. Its getToken() renews the
// access token first when it is about to expire.
export const session = new LumoAuthSession({ auth, redirectUri });
// Creates the PKCE verifier and sends the browser to the hosted page.
export async function signIn(): Promise<void> {
const { url, codeVerifier, state } = await session.buildAuthorizationUrl();
sessionStorage.setItem('pkce', JSON.stringify({ codeVerifier, state }));
window.location.href = url;
}
// On the callback address: exchanges the code for tokens.
export async function finishSignIn(): Promise<void> {
const params = new URLSearchParams(window.location.search);
const saved = JSON.parse(sessionStorage.getItem('pkce') ?? '{}');
sessionStorage.removeItem('pkce');
const code = params.get('code');
if (params.get('error')) throw new Error(params.get('error_description') ?? params.get('error')!);
// The state must be the value that this browser sent.
if (!code || !saved.state || params.get('state') !== saved.state) {
throw new Error('The callback does not belong to a sign-in that this browser started.');
}
const tokens = await auth.exchangeCodeForTokens({ code, codeVerifier: saved.codeVerifier, redirectUri });
await session.adopt(tokens);
}
// Removes the tokens, then ends the session at LumoAuth as well.
export async function signOut(): Promise<void> {
const { idToken } = session.getTokens();
await session.clearSession();
window.location.href = auth.buildEndSessionUrl({
idTokenHint: idToken ?? undefined,
postLogoutRedirectUri: window.location.origin + '/',
});
}
// The start page: a sign-in button, or the profile of the signed-in person.
import { Component, OnInit, signal } from '@angular/core';
import type { UserInfo } from '@lumoauth/client';
import { auth, callbackPath, finishSignIn, session, signIn, signOut } from './auth';
@Component({
selector: 'app-root',
template: `
<main>
<h1>Sign in through the hosted page</h1>
@if (error()) {
<p role="alert">Sign-in did not finish: {{ error() }}</p>
}
@if (status() === 'unauthenticated') {
<p>Nobody is signed in.</p>
<button type="button" (click)="signIn()">Sign in</button>
}
@if (user(); as person) {
<p>Signed in as {{ person.email }}</p>
<p>Name: {{ person.name }}</p>
<button type="button" (click)="callApi()">Call the API</button>
<p>{{ answer() }}</p>
<button type="button" (click)="signOut()">Sign out</button>
}
</main>
`,
})
export class App implements OnInit {
protected readonly status = signal('loading');
protected readonly user = signal<UserInfo | null>(null);
protected readonly answer = signal('');
protected readonly error = signal('');
protected readonly signIn = signIn;
protected readonly signOut = signOut;
async ngOnInit(): Promise<void> {
try {
if (window.location.pathname === callbackPath) {
await finishSignIn();
window.history.replaceState({}, '', '/');
}
// Reads the tokens that an earlier page load stored.
await session.hydrate();
if (session.getSnapshot().isSignedIn) {
this.user.set(await auth.getUserInfo((await session.getToken())!));
}
} catch (reason) {
this.error.set((reason as Error).message);
}
this.status.set(session.getSnapshot().status);
}
// getToken() returns the access token and renews it first when it is about
// to expire. Send it to your own API in the same way.
protected async callApi(): Promise<void> {
const token = (await session.getToken())!;
const info = await auth.getUserInfo(token);
this.answer.set(`UserInfo with the access token: sub ${info.sub}`);
}
}
{
"name": "lumoauth-recipe-hosted-page-angular",
"private": true,
"scripts": {
"start": "ng serve --port 3000 --define \"LUMOAUTH_URL='${LUMOAUTH_URL:-https://app.lumoauth.dev}'\" --define \"LUMOAUTH_ORG_ID='$LUMOAUTH_ORG_ID'\" --define \"LUMOAUTH_CLIENT_ID='$LUMOAUTH_CLIENT_ID'\"",
"build": "ng build"
},
"dependencies": {
"@angular/common": "^22.3.0",
"@angular/compiler": "^22.3.0",
"@angular/core": "^22.3.0",
"@angular/platform-browser": "^22.3.0",
"@lumoauth/client": "^1.7.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.3.0",
"@angular/cli": "^22.3.0",
"@angular/compiler-cli": "^22.3.0",
"typescript": "~6.0.2"
}
}
cd sign-in/hosted-page/js/angular && npm install && npm start
Open http://localhost:3000. The start script passes the three variables to the browser code.
Check the result
Click Sign in. The address bar shows the sign-in page of your organization, not a form in your app. After sign-in the app shows these lines. The third line appears when you click Call the API.
Signed in as dana.reyes@example.com
Name: Dana Reyes
UserInfo with the access token: sub 01a21fb9-10a3-7e59-b71d-8cc6d9bb53ce
- The recipe calls the UserInfo endpoint. Send the access token to your own API in the same way.
- The audit log of the organization has a
user.loginevent for the sign-in. Open Audit logs in the portal. - Click Sign out. The Starter App then stops on the page "You have been logged out" of your organization.
- To return to your app after sign-out, add its address to the application. Open the Configuration tab, and under Logout add
http://localhost:5173/to Post-logout redirect URIs.
Limits
- The tokens are in
sessionStorage, so each browser tab signs in for itself. Choose where tokens are stored compares the other stores. - The app gets a refresh token only when the grant types of the application include
refresh_token. A new application has it. The scopeoffline_accessdoes not change this. - The redirect URI is matched exactly. An address with another port or another path is refused.