Implement a secure OAuth2 login flow with PKCE in a Vue.js application.
- User
Implement a secure OAuth2 login flow with PKCE in a Vue.js application.
- Assistant
Planning OAuth2 Implementation
The user wants to implement a secure OAuth2 login flow with PKCE in a Vue.js application. They likely need guidance and code examples for integrating with OAuth 2.0, including generating code_verifier and challenge, redirect handling, and token exchange. They didn’t specify an OAuth provider, so I’ll keep it somewhat generic while illustrating with Authorization Server endpoints.
I'm thinking Vue 3 with the composition API and Vite would be the way to go, and I should address storing tokens securely to enhance safety.Outlining PKCE Steps
I need to cover the essential PKCE steps, starting with generating a random string (code_verifier) and utilizing sha256 and base64url formats. For implementation, I’ll use methods like
crypto.getRandomValuesandwindow.crypto.subtle.digest. The user may want step-by-step instructions, so I should maintain a balance of being concise yet detailed enough to ensure clarity.I’ll structure my answer to include an overview of OAuth2 + PKCE, assumptions regarding the Vue 3 setup, and a list of utility functions for PKCE.Detailing Authentication Service Steps
Next, I'll outline the authentication service functions:
login,handleCallback,getAccessToken, andlogout.For the
login()function, I’ll generate state, code_verifier, and challenge, storing them in sessionStorage before building the auth URL and redirecting. In the callback handling, I’ll read parameters such as code, state, and error, validating state and exchanging the code for tokens via POST to the token endpoint.I also need to integrate this with Vue and include best security practices, ensuring the code remains provider-agnostic while using JavaScript for simplicity.Structuring OAuth2 in TypeScript
I realize many developers prefer TypeScript, so I’ll mention that this code is JavaScript but friendly for TypeScript. I plan to create an
authService.jsfile that includes configuration settings likeclientId,authorizationEndpoint,tokenEndpoint,redirectUri, andscopes.I’ll define necessary functions, like
login(), and showcase how to compute sha256 in the browser using the TextEncoder and crypto API. Also, I’ll include thebase64UrlEncodefunction to handle encoding, discussing how to generate a random string with an appropriate character length.Configuring the Router and Handling TokensNext, I’ll show a sample router configuration using Vue Router, where I’ll import required functions like
handleRedirectCallbackandisAuthenticated.In the routes, I'll include paths for the home component, a callback component, and a protected route that requires authentication. The redirection after login can be managed by using a 'state' parameter.
When receiving the response from the token endpoint, it usually returns JSON with tokens, which I’d store in memory and optionally in sessionStorage. Adding an axios interceptor will help manage token authorization in requests, and I’ll discuss a function to handle token refreshing.
Finally, I need to ensure the solution is clear and accessible, providing both step-by-step guidance and code samples as the user requested. Below is a complete, browser‑only OAuth 2.0 Authorization Code with PKCE flow for a Vue.js SPA (Vue 3 + Vue Router). Adapt the endpoints and client IDs to your provider (Auth0, Okta, Keycloak, custom IdP, etc.).
1. Prerequisites & assumptions
- Vue 3 app (Vite or Vue CLI)
- Vue Router
- An OAuth2/OIDC provider that supports:
- Authorization Code + PKCE
- CORS on
/tokenendpoint (or a lightweight backend proxy)
- A registered OAuth client with:
- Redirect URI:
https://your-app.example.com/callback - Public client (no client secret in the SPA)
- Redirect URI:
2. OAuth config
Create
src/auth/config.js:// src/auth/config.js export const oauthConfig = { clientId: import.meta.env.VITE_OAUTH_CLIENT_ID, authorizationEndpoint: 'https://auth.example.com/oauth2/authorize', tokenEndpoint: 'https://auth.example.com/oauth2/token', logoutEndpoint: 'https://auth.example.com/logout', // optional redirectUri: window.location.origin + '/callback', scopes: 'openid profile email', // add more if needed };Set env var in
.env:VITE_OAUTH_CLIENT_ID=your_client_id_here
3. PKCE helpers
Create
src/auth/pkce.js:// src/auth/pkce.js // Generates a high-entropy random string (code_verifier, state) export function generateRandomString(length = 64) { const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; const randomValues = new Uint8Array(length); crypto.getRandomValues(randomValues); return Array.from(randomValues, v => charset[v % charset.length]).join(''); } function base64UrlEncode(arrayBuffer) { const bytes = new Uint8Array(arrayBuffer); let binary = ''; for (let i = 0; i < bytes.byteLength; i++) { binary += String.fromCharCode(bytes[i]); } return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } export async function pkceChallengeFromVerifier(verifier) { const encoder = new TextEncoder(); const data = encoder.encode(verifier); const digest = await crypto.subtle.digest('SHA-256', data); return base64UrlEncode(digest); }
4. Auth service (login, callback, tokens)
Create
src/auth/authService.js:// src/auth/authService.js import { oauthConfig } from './config'; import { generateRandomString, pkceChallengeFromVerifier } from './pkce'; const CODE_VERIFIER_KEY = 'pkce_code_verifier'; const OAUTH_STATE_KEY = 'oauth_state'; const TOKEN_STORAGE_KEY = 'oauth_tokens'; // In-memory cache of tokens (preferred over always reading storage) let tokenData = null; // --- STORAGE HELPERS --- function saveTokens(tokens) { tokenData = { ...tokens, expires_at: Date.now() + tokens.expires_in * 1000, }; // Use sessionStorage as a compromise; avoid localStorage if you can. sessionStorage.setItem(TOKEN_STORAGE_KEY, JSON.stringify(tokenData)); } function loadTokens() { if (tokenData) return tokenData; const raw = sessionStorage.getItem(TOKEN_STORAGE_KEY); if (!raw) return null; tokenData = JSON.parse(raw); return tokenData; } function clearTokens() { tokenData = null; sessionStorage.removeItem(TOKEN_STORAGE_KEY); } // --- PUBLIC HELPERS --- export function isAuthenticated() { const tokens = loadTokens(); return !!tokens && tokens.expires_at > Date.now(); } export function getAccessToken() { const tokens = loadTokens(); if (!tokens) return null; if (tokens.expires_at <= Date.now()) return null; // no refresh here yet return tokens.access_token; } // --- LOGIN FLOW --- export async function login(returnPath = '/') { const state = generateRandomString(32); const codeVerifier = generateRandomString(64); const codeChallenge = await pkceChallengeFromVerifier(codeVerifier); sessionStorage.setItem(CODE_VERIFIER_KEY, codeVerifier); sessionStorage.setItem(OAUTH_STATE_KEY, JSON.stringify({ state, returnPath })); const params = new URLSearchParams({ client_id: oauthConfig.clientId, response_type: 'code', redirect_uri: oauthConfig.redirectUri, scope: oauthConfig.scopes, state, code_challenge: codeChallenge, code_challenge_method: 'S256', }); window.location.assign(`${oauthConfig.authorizationEndpoint}?${params.toString()}`); } // --- CALLBACK HANDLER --- export async function handleRedirectCallback(url = window.location.href) { const parsed = new URL(url); const code = parsed.searchParams.get('code'); const state = parsed.searchParams.get('state'); const error = parsed.searchParams.get('error'); if (error) { throw new Error(`OAuth error: ${error}`); } if (!code || !state) { throw new Error('Missing code or state'); } // Validate state const stored = sessionStorage.getItem(OAUTH_STATE_KEY); if (!stored) throw new Error('Missing stored state'); const { state: storedState, returnPath } = JSON.parse(stored); if (state !== storedState) throw new Error('Invalid state'); const codeVerifier = sessionStorage.getItem(CODE_VERIFIER_KEY); if (!codeVerifier) throw new Error('Missing code_verifier'); // Exchange authorization code for tokens const body = new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: oauthConfig.redirectUri, client_id: oauthConfig.clientId, code_verifier: codeVerifier, }); const resp = await fetch(oauthConfig.tokenEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body, }); if (!resp.ok) { const text = await resp.text(); throw new Error(`Token endpoint error: ${resp.status} ${text}`); } const tokenResponse = await resp.json(); saveTokens(tokenResponse); // Clean PKCE data sessionStorage.removeItem(CODE_VERIFIER_KEY); sessionStorage.removeItem(OAUTH_STATE_KEY); return { tokens: tokenResponse, returnPath }; } // --- LOGOUT --- export function logout() { clearTokens(); // Simple client-side logout // If your IdP supports RP-initiated logout, redirect there: if (oauthConfig.logoutEndpoint) { const params = new URLSearchParams({ client_id: oauthConfig.clientId, post_logout_redirect_uri: window.location.origin, }); window.location.assign(`${oauthConfig.logoutEndpoint}?${params.toString()}`); } else { window.location.assign('/'); } }
5. Vue Router integration
Create
src/router/index.js:// src/router/index.js import { createRouter, createWebHistory } from 'vue-router'; import HomeView from '../views/HomeView.vue'; import ProtectedView from '../views/ProtectedView.vue'; import CallbackView from '../views/CallbackView.vue'; import { isAuthenticated, login } from '../auth/authService'; const routes = [ { path: '/', name: 'home', component: HomeView }, { path: '/protected', name: 'protected', component: ProtectedView, meta: { requiresAuth: true }, }, { path: '/callback', name: 'callback', component: CallbackView, // lightweight view that just handles the callback }, ]; const router = createRouter({ history: createWebHistory(), routes, }); router.beforeEach(async (to, from, next) => { if (to.meta.requiresAuth && !isAuthenticated()) { // redirect to login; pass desired return path await login(to.fullPath); return; // login() will redirect away } next(); }); export default router;
6. Callback view
Create
src/views/CallbackView.vue:<template> <div>Signing you in...</div> </template> <script setup> import { onMounted } from 'vue'; import { useRouter, useRoute } from 'vue-router'; import { handleRedirectCallback } from '../auth/authService'; const router = useRouter(); const route = useRoute(); onMounted(async () => { try { const { returnPath } = await handleRedirectCallback( window.location.origin + route.fullPath ); // Clean query params from URL router.replace(returnPath || '/'); } catch (e) { console.error(e); router.replace({ name: 'home', query: { authError: '1' } }); } }); </script>
7. Use tokens in API calls
Example with Axios:
// src/api/http.js import axios from 'axios'; import { getAccessToken, logout } from '../auth/authService'; const http = axios.create({ baseURL: 'https://api.example.com', }); http.interceptors.request.use(config => { const token = getAccessToken(); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); http.interceptors.response.use( resp => resp, error => { if (error.response?.status === 401) { // Optional: try refresh here before logging out logout(); } return Promise.reject(error); } ); export default http;
8. Basic UI usage
Example
HomeView.vue:<template> <div> <h1>Home</h1> <p v-if="authenticated">You are logged in.</p> <p v-else>You are not logged in.</p> <button v-if="!authenticated" @click="onLogin">Login</button> <button v-else @click="onLogout">Logout</button> <router-link to="/protected">Go to protected page</router-link> </div> </template> <script setup> import { computed } from 'vue'; import { login, logout, isAuthenticated } from '../auth/authService'; const authenticated = computed(() => isAuthenticated()); const onLogin = () => login('/'); const onLogout = () => logout(); </script>Example
ProtectedView.vue:<template> <div> <h1>Protected</h1> <p>This page requires login.</p> </div> </template> <script setup> // route guard already enforces auth </script>
9. Security notes / best practices
- Always use HTTPS in production.
- Use PKCE (
code_challenge_method=S256) and validatestateto prevent CSRF. - Prefer in‑memory tokens; if you must persist,
sessionStorageis safer thanlocalStorage. - If your provider allows refresh tokens in SPAs, use the
refresh_tokengrant and rotate tokens; implementrefreshToken()inauthService.js. - If possible, move the token exchange to a backend and issue your own cookies (most secure), but the above shows a pure SPA flow.
If you share which provider you use (Auth0, Keycloak, etc.), I can adapt the endpoints and parameters to a plug‑and‑play example.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.