Skip to main content

Vue SDK

The Idenplane Vue SDK provides Vue 3-specific bindings for the idenplane-sdk, including an IdenplanePlugin, composables (useAuth, useUser, usePermissions), a Vue Router navigation guard (createAuthGuard), and an AuthProvider component for scoped authentication context.

Installation​

npm install idenplane-vue idenplane-sdk vue

Quick Start​

1. Create One Client and Install the Plugin​

Create the client in its own module, so the plugin, the router guard and your components share one instance (one session, one init()):

// auth.ts
import { IdenplaneClient } from 'idenplane-vue';

export const idenplane = new IdenplaneClient({
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:5173/callback',
});
// main.ts
import { createApp } from 'vue';
import { IdenplanePlugin } from 'idenplane-vue';
import App from './App.vue';
import router from './router';
import { idenplane } from './auth';

const app = createApp(App);
app.use(IdenplanePlugin, { client: idenplane });
app.use(router);
app.mount('#app');

2. Use Composables in Components​

<script setup lang="ts">
import { useAuth } from 'idenplane-vue';

const { isAuthenticated, user, login, logout, isLoading } = useAuth();
</script>

<template>
<div v-if="isLoading">Loading...</div>
<div v-else-if="isAuthenticated">
Hello, {{ user?.name }}
<button @click="logout">Sign out</button>
</div>
<div v-else>
<button @click="login()">Sign in</button>
</div>
</template>

3. Protect Routes with the Navigation Guard​

// router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
import { createAuthGuard } from 'idenplane-vue';
import { idenplane } from '../auth'; // the client the plugin was given

const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/login', component: Login },
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true },
},
{
path: '/admin',
component: Admin,
meta: { requiresAuth: true, roles: ['admin'] },
},
],
});

router.beforeEach(createAuthGuard({ loginRoute: '/login' }, idenplane));

export default router;

IdenplanePlugin​

The IdenplanePlugin is a Vue 3 plugin that provides one IdenplaneClient to every component (for the composables) and starts its init() (discovery and session restore) right away. Give it an existing client — app.use(IdenplanePlugin, { client }) or app.use(IdenplanePlugin, client) — to share that client with code outside components, such as the router guard. Or give it a configuration and let it create the client.

Plugin Options​

OptionTypeRequiredDescription
urlstringYesIdenplane server URL
realmstringYesRealm name
clientIdstringYesOAuth2 client ID
redirectUristringYesRedirect URI after login
scopesstring[]NoOAuth2 scopes (default: ['openid', 'profile', 'email'])
storage'sessionStorage' | 'localStorage' | 'memory'NoToken storage type (default: memory)
autoRefreshbooleanNoEnable automatic token refresh (default: true)
refreshBuffernumberNoSeconds before expiry to trigger refresh (default: 30)
onLogin(tokens: TokenResponse) => voidNoCalled on successful login
onLogout() => voidNoCalled on logout
onError(error: Error) => voidNoCalled on authentication error

With Inline Config​

// main.ts
import { createApp } from 'vue';
import { IdenplanePlugin } from 'idenplane-vue';
import App from './App.vue';

const app = createApp(App);

app.use(IdenplanePlugin, {
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:5173/callback',
scopes: ['openid', 'profile', 'email', 'custom:scope'],
storage: 'localStorage',
autoRefresh: true,
refreshBuffer: 30,
onLogin: (tokens) => {
console.log('Access token:', tokens.access_token);
},
onLogout: () => {
console.log('User signed out');
},
});

app.mount('#app');

With Pre-built Client​

For more control over the client configuration, or to share it with a router guard:

// main.ts
import { createApp } from 'vue';
import { IdenplanePlugin } from 'idenplane-vue';
import { IdenplaneClient } from 'idenplane-vue';
import App from './App.vue';

const authClient = new IdenplaneClient({
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:5173/callback',
storage: 'sessionStorage',
autoRefresh: true,
refreshBuffer: 30,
});

const app = createApp(App);

app.use(IdenplanePlugin, { client: authClient });

app.mount('#app');

useAuth Composable​

The useAuth composable provides access to authentication state and actions:

const {
client, // IdenplaneClient - the SDK client instance
isAuthenticated, // boolean - whether user is authenticated
isLoading, // boolean - whether auth state is loading
user, // UserInfo | null - current user info
login, // (options?) => Promise<void> - initiate login
logout, // () => Promise<void> - sign out
getToken, // () => string | null - get current access token
} = useAuth();

Example: Login Component​

<script setup lang="ts">
import { useAuth } from 'idenplane-vue';

const { isAuthenticated, isLoading, login, logout } = useAuth();

const handleLogin = async () => {
try {
await login();
} catch (error) {
console.error('Login failed:', error);
}
};
</script>

<template>
<div v-if="isLoading">Loading...</div>
<div v-else-if="isAuthenticated">
<button @click="logout">Sign Out</button>
</div>
<div v-else>
<button @click="handleLogin">Sign In with Idenplane</button>
</div>
</template>

Example: Accessing the Token​

<script setup lang="ts">
import { useAuth } from 'idenplane-vue';

const { getToken, isAuthenticated } = useAuth();

const token = getToken();
</script>

<template>
<div v-if="isAuthenticated" class="token-display">
<p>Your access token:</p>
<code>{{ token?.substring(0, 20) }}...</code>
</div>
</template>

Example: Login with Custom Options​

<script setup lang="ts">
import { useAuth } from 'idenplane-vue';

const { login } = useAuth();

const handleLogin = async () => {
try {
await login({
scope: ['openid', 'profile', 'email', 'custom:scope'],
});
} catch (error) {
console.error('Login failed:', error);
}
};
</script>

<template>
<button @click="handleLogin">Sign In with Custom Scope</button>
</template>

useUser Composable​

The useUser composable returns the current user's information from the ID token claims:

const user = useUser();
// Returns: ComputedRef<UserInfo | null>

interface UserInfo {
sub: string; // User ID
name?: string; // Display name
email?: string; // Email address
emailVerified?: boolean;
picture?: string; // Avatar URL
roles?: string[]; // Assigned roles
permissions?: string[]; // Direct permissions
[key: string]: any; // Any custom claims
}

Example: User Profile Card​

<script setup lang="ts">
import { useUser } from 'idenplane-vue';

const user = useUser();
</script>

<template>
<div v-if="user" class="profile-card">
<img
v-if="user.picture"
:src="user.picture"
:alt="user.name"
class="avatar"
/>
<h2>{{ user.name || 'User' }}</h2>
<p>{{ user.email }}</p>
<span v-if="user.emailVerified">Email verified</span>
<span v-else>Email not verified</span>
</div>
<div v-else>
<p>Not signed in</p>
</div>
</template>

usePermissions Composable​

The usePermissions composable provides role and permission checking:

const {
roles, // string[] - all assigned roles
permissions, // string[] - all direct permissions
hasRole, // (role: string) => boolean
hasPermission, // (permission: string) => boolean
hasAnyRole, // (roles: string[]) => boolean
hasAllRoles, // (roles: string[]) => boolean
} = usePermissions();

Example: Role-Based UI​

<script setup lang="ts">
import { usePermissions } from 'idenplane-vue';

const { hasRole, hasPermission, roles } = usePermissions();
</script>

<template>
<div class="dashboard">
<h1>Dashboard</h1>

<!-- Admin-only section -->
<section v-if="hasRole('admin')">
<h2>Admin Panel</h2>
<a href="/admin">Go to Admin</a>
</section>

<!-- Content with multiple role check -->
<section v-if="hasAnyRole(['editor', 'admin'])">
<h2>Content Editor</h2>
<button>Edit Content</button>
</section>

<!-- Permission-based access -->
<section v-if="hasPermission('read:reports')">
<h2>Reports</h2>
<button>View Reports</button>
</section>

<!-- Fallback for unauthorized -->
<p v-if="!hasRole('admin')">
You don't have admin access.
</p>
</div>
</template>

Example: Multi-Role Check​

<script setup lang="ts">
import { usePermissions } from 'idenplane-vue';

const { hasAllRoles } = usePermissions();

const canAccessModeration = hasAllRoles(['moderator', 'content-editor']);
</script>

<template>
<div v-if="canAccessModeration">
<h2>Moderation Tools</h2>
<!-- Moderation UI -->
</div>
<div v-else>
<p>You need both moderator and content-editor roles.</p>
</div>
</template>

The createAuthGuard function creates a Vue Router navigation guard for route protection:

const guard = createAuthGuard(options?, client?);

Pass the client as the second argument — the same instance you gave the plugin or <AuthProvider :client>. A guard registered in router/index.ts runs outside any component, where inject() cannot reach the plugin's client, so the explicit client is the reliable way to share it. (On Vue 3.3+ with vue-router 4.2+, a guard created without a client looks it up from the app when it runs.)

Routes without requiresAuth or roles, and the login route itself, are never redirected. If no client can be found for a protected route, the guard fails closed and redirects to the login route with ?next=<path>. A user without the required roles is sent to the login route with ?error=forbidden.

Guard Options​

OptionTypeRequiredDescription
loginRoutestringNoRedirect path for unauthenticated users (default: '/login')
rolesstring[]NoRoles required on every route (except the login route); meta.roles overrides it per route

Basic Usage​

// router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
import { createAuthGuard } from 'idenplane-vue';
import { idenplane } from '../auth';

const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/login', component: Login },
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true },
},
],
});

router.beforeEach(createAuthGuard({ loginRoute: '/login' }, idenplane));

export default router;

Route-Level Role Protection​

// router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
import { createAuthGuard } from 'idenplane-vue';
import { idenplane } from '../auth';

const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/login', component: Login },
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true },
},
{
path: '/admin',
component: Admin,
meta: { requiresAuth: true, roles: ['admin'] },
},
{
path: '/moderator',
component: Moderator,
meta: { requiresAuth: true, roles: ['moderator', 'content-editor'] },
},
],
});

router.beforeEach(createAuthGuard({ loginRoute: '/login' }, idenplane));

export default router;

AuthProvider Component​

The AuthProvider component provides a client to a component subtree, instead of the plugin, and starts its init() (discovery and session restore) in the browser. Use it when you need multiple auth configurations or isolated auth state:

<!-- App.vue -->
<template>
<AuthProvider
url="http://localhost:3000"
realm="my-realm"
client-id="my-app"
redirect-uri="http://localhost:5173/callback"
>
<RouterView />
</AuthProvider>
</template>

<script setup lang="ts">
import { AuthProvider } from 'idenplane-vue';
</script>

AuthProvider Props​

PropTypeRequiredDescription
clientIdenplaneClientYes*Pre-built client instance (for example the one your router guard uses)
urlstringYes*Idenplane server URL
realmstringYes*Realm name
client-idstringYes*OAuth2 client ID
redirect-uristringYes*Redirect URI after login
scopesstring[]NoOAuth2 scopes
storage'sessionStorage' | 'localStorage' | 'memory'NoToken storage (default: sessionStorage)
auto-refreshbooleanNoAutomatic token refresh (default: true)

*Either a client prop or all of url, realm, clientId, and redirectUri are required.

With Pre-built Client​

<!-- App.vue -->
<template>
<AuthProvider :client="authClient">
<RouterView />
</AuthProvider>
</template>

<script setup lang="ts">
import { AuthProvider } from 'idenplane-vue';
import { idenplane as authClient } from './auth'; // shared with the router guard
</script>

API Reference​

Plugin​

ExportDescription
IdenplanePluginVue 3 plugin: app.use(IdenplanePlugin, { client }) to provide an existing client, or app.use(IdenplanePlugin, IdenplaneConfig)

Composables​

ExportDescription
useAuth()Returns { client, isAuthenticated, isLoading, user, login, logout, getToken }
useUser()Returns ComputedRef<UserInfo | null>
usePermissions()Returns { roles, permissions, hasRole, hasPermission, hasAnyRole, hasAllRoles }
ExportDescription
createAuthGuard(options?, client?)Creates a NavigationGuard for Vue Router; pass the shared client

Components​

ExportDescription
AuthProviderProvides a client to a component subtree and calls its init()

Types​

interface IdenplaneConfig {
url: string;
realm: string;
clientId: string;
redirectUri: string;
scope?: string[];
storage?: 'sessionStorage' | 'localStorage' | 'memory';
autoRefresh?: boolean;
refreshBuffer?: number;
onLogin?: (tokens: TokenResponse) => void;
onLogout?: () => void;
onError?: (error: Error) => void;
}

interface UserInfo {
sub: string;
name?: string;
email?: string;
emailVerified?: boolean;
picture?: string;
roles?: string[];
permissions?: string[];
[key: string]: any;
}

interface TokenResponse {
access_token: string;
token_type: string;
expires_in: number;
refresh_token?: string;
id_token?: string;
scope?: string;
}

TypeScript Support​

The SDK is written in TypeScript and provides full type definitions:

import type {
IdenplaneClient,
IdenplaneConfig,
TokenResponse,
UserInfo,
} from 'idenplane-sdk';

import {
useAuth,
useUser,
usePermissions,
AuthProvider,
createAuthGuard,
} from 'idenplane-vue';

// All composables are fully typed
function MyComponent() {
const user = useUser(); // ComputedRef<UserInfo | null>
const { isAuthenticated } = useAuth(); // Fully typed
const { hasRole } = usePermissions(); // Fully typed
}

Next Steps​

Quickstart Set up Idenplane and create your first authenticated Vue app

Configuration Learn about all configuration options

API Reference Complete REST API documentation

React SDK React-specific hooks and components


idenplane.com · GitHub · Discord