Initiating the OAuth2 Project
I'm focused on implementing a secure OAuth2 login flow with PKCE in Vue.js. I've begun to define the project's goal. I need to ensure the application's security and modern approach to authentication.
Defining Project Strategy
I'm now weighing the implementation strategy, comparing manual crypto versus leveraging a library. Manual implementation seems educational, but I quickly realized the risks of maintenance debt. I'm leaning heavily towards a vetted library like oidc-client-ts for its robust handling of OAuth2 and PKCE complexities.
Analyzing Implementation Details
Now I'm breaking down the project into steps. I've decided to use oidc-client-ts and pinia. The architecture is coming together: an authentication service using UserManager from oidc-client-ts to wrap OIDC client logic, a Pinia store for reactivity, and router guards for route protection. The callback component will handle token exchange.
Formulating the Implementation Guide
I'm now outlining the guide. I've broken down the project into logical sections. My focus is on concise explanations, the configuration files, and the AuthService. The setup instructions will be detailed, and the code examples will demonstrate the core logic. I'm prioritizing clarity and ease of use for the reader.
Analyzing Project Steps
I'm now fully immersed in the step-by-step logic. The essential components are mapped out, from the Vue.js frontend and state management with Pinia, to routing with guards and the crucial OAuth2/PKCE implementation. I've sketched out the AuthService wrapper, the Pinia store, callback handling, login actions, and route protection with an API interceptor.
This is a comprehensive guide to implementing a secure Authorization Code Flow with PKCE (Proof Key for Code Exchange) in Vue.js.
For production-grade security and maintenance, it is highly recommended to use a certified library rather than writing the cryptographic PKCE logic (SHA-256 hashing and Base64 URL encoding) from scratch.
We will use oidc-client-ts. It is the modern, maintained successor to the popular oidc-client library.
Prerequisites
- Vue 3 Project (TypeScript recommended)
- Pinia (for state management)
- Vue Router
Step 1: Install Dependencies
npm install oidc-client-ts pinia axios
Step 2: OIDC Configuration
Create a file to hold your OAuth provider settings. These details come from your Auth Provider (Auth0, Keycloak, AWS Cognito, IdentityServer, etc.).
src/config/auth.ts
import { UserManagerSettings, WebStorageStateStore } from 'oidc-client-ts';
export const authSettings: UserManagerSettings = {
// URL of your Identity Provider
authority: 'https://your-auth-server.com/realms/myrealm',
// Your Client ID registered with the provider
client_id: 'my-vue-app',
// The URI the auth server redirects to after login
redirect_uri: window.location.origin + '/auth/callback',
// The URI the auth server redirects to after logout
post_logout_redirect_uri: window.location.origin,
// "code" implies PKCE flow
response_type: 'code',
// Scopes to request (openid and profile are standard)
scope: 'openid profile email',
// Store tokens in localStorage (default is sessionStorage)
userStore: new WebStorageStateStore({ store: window.localStorage }),
// silent renew attempts to refresh token before it expires
automaticSilentRenew: true,
};
Step 3: The Auth Service
This singleton manages the oidc-client-ts instance. It abstracts the library away from your components.
src/services/authService.ts
import { UserManager, User } from 'oidc-client-ts';
import { authSettings } from '@/config/auth';
class AuthService {
private userManager: UserManager;
constructor() {
this.userManager = new UserManager(authSettings);
// Optional: Logger logs
// Log.setLogger(console);
// Log.setLevel(Log.INFO);
}
public getUser(): Promise<User | null> {
return this.userManager.getUser();
}
public login(): Promise<void> {
return this.userManager.signinRedirect();
}
public logout(): Promise<void> {
return this.userManager.signoutRedirect();
}
// This handles the code exchange after redirect
public handleCallback(): Promise<User> {
return this.userManager.signinRedirectCallback();
}
// Get the raw access token for API calls
public async getAccessToken(): Promise<string | null> {
const user = await this.getUser();
return user ? user.access_token : null;
}
}
export default new AuthService();
Step 4: Pinia Auth Store
Use Pinia to make the user state available reactively throughout your app.
src/stores/auth.ts
import { defineStore } from 'pinia';
import authService from '@/services/authService';
import type { User } from 'oidc-client-ts';
interface AuthState {
user: User | null;
loading: boolean;
error: string | null;
}
export const useAuthStore = defineStore('auth', {
state: (): AuthState => ({
user: null,
loading: true,
error: null,
}),
getters: {
isAuthenticated: (state) => !!state.user && !state.user.expired,
username: (state) => state.user?.profile.preferred_username || state.user?.profile.name,
},
actions: {
async initializeAuth() {
try {
this.user = await authService.getUser();
} catch (err) {
console.error('Auth init failed', err);
this.user = null;
} finally {
this.loading = false;
}
},
async login() {
await authService.login();
},
async logout() {
await authService.logout();
this.user = null;
},
async handleLoginCallback() {
try {
this.loading = true;
this.user = await authService.handleCallback();
// Remove the auth code from the URL to keep it clean
window.history.replaceState({}, document.title, window.location.pathname);
} catch (err: any) {
this.error = err.message;
console.error('Login callback failed', err);
} finally {
this.loading = false;
}
}
}
});
Step 5: The Callback Component
This is the dedicated route handler that processes the logic when the user comes back from the Auth Server (redirect_uri defined in Step 2).
src/views/AuthCallback.vue
<template>
<div class="callback-container">
<div v-if="error">Error: {{ error }}</div>
<div v-else>Processing login...</div>
</div>
</template>
<script setup lang="ts">
import { onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
const router = useRouter();
const authStore = useAuthStore();
const error = computed(() => authStore.error);
onMounted(async () => {
await authStore.handleLoginCallback();
if (authStore.isAuthenticated) {
// Redirect to dashboard or the page they originally requested
router.push({ name: 'Dashboard' });
} else {
// Handle failure (redirect to home or show error)
router.push({ name: 'Home' });
}
});
</script>
Step 6: Router Configuration
Set up the routes and the Navigation Guard to protect specific pages.
src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import HomeView from '@/views/HomeView.vue';
import AuthCallback from '@/views/AuthCallback.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', name: 'Home', component: HomeView },
{ path: '/auth/callback', name: 'Callback', component: AuthCallback },
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { requiresAuth: true }
}
]
});
// Navigation Guard
router.beforeEach(async (to, from, next) => {
const authStore = useAuthStore();
// Ensure auth is checked before routing
if (authStore.loading) {
await authStore.initializeAuth();
}
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
// Optional: Save the location to redirect back after login
await authStore.login();
// The login redirects the window, so logic stops here.
return;
}
next();
});
export default router;
Step 7: Using Axios Interceptor (The "Secure" Part)
You must attach the access token to your API requests.
src/services/api.ts
import axios from 'axios';
import authService from '@/services/authService';
const api = axios.create({
baseURL: 'https://api.your-backend.com'
});
api.interceptors.request.use(
async (config) => {
const token = await authService.getAccessToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
api.interceptors.response.use(
(response) => response,
async (error) => {
// Handle 401 Errors (Token expired/invalid)
if (error.response && error.response.status === 401) {
// Optional: Trigger logout or refresh logic here
// Note: oidc-client-ts handles auto-refresh, so a 401 usually means
// the session is completely dead.
}
return Promise.reject(error);
}
);
export default api;
Step 8: App Entry Point
Ensure the store is initialized when the app mounts.
src/App.vue
<template>
<div v-if="authStore.loading">Loading User Context...</div>
<div v-else>
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/dashboard">Dashboard</router-link>
<button v-if="!authStore.isAuthenticated" @click="authStore.login">
Login
</button>
<button v-else @click="authStore.logout">
Logout ({{ authStore.username }})
</button>
</nav>
<router-view />
</div>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
import { useAuthStore } from '@/stores/auth';
const authStore = useAuthStore();
onMounted(() => {
authStore.initializeAuth();
});
</script>
How PKCE Works here
- User clicks Login:
oidc-client-ts generates a random code_verifier and hashes it to create a code_challenge.
- Redirect: The user is redirected to the Auth Server with the
code_challenge. The code_verifier is saved in LocalStorage/SessionStorage.
- Auth Server: User logs in. The Auth server returns an Authorization Code via the Redirect URL.
- Callback:
oidc-client-ts takes the Code and the stored code_verifier and sends them via POST to the token endpoint.
- Verification: The Auth Server hashes the
code_verifier. If it matches the code_challenge sent in step 2, it issues the Access Token.
- Security: Even if a malicious actor intercepts the Code in the URL, they cannot exchange it for a token because they do not have the random
code_verifier stored in your browser's storage.