Vue OIDC Login with Entra ID Integration
A comprehensive guide to implementing OIDC authentication in Vue using Microsoft Entra ID
Highlights
- Seamless Integration: Use OIDC standards along with Microsoft Entra ID for secure, single sign-on experiences in Vue.
- End-to-End Process: A step-by-step process covering application registration, configuration, code implementation, and route protection.
- Robust Code Examples: Detailed code snippets using libraries like oidc-client for authentication and token management.
Overview
Integrating OpenID Connect (OIDC) login with Microsoft Entra ID into your Vue.js application provides an efficient and secure approach to handle user authentication and single sign-on (SSO). This guide explains the complete process of setting up your Entra ID configuration, registering your Vue application, and using key libraries and code implementations to establish a robust OIDC flow. By following these guidelines, you can ensure that your Vue application communicates reliably with Entra ID, leveraging industry standards to manage identity securely.
Step 1: Registering Your Application with Microsoft Entra ID
Creating Your Entra ID Application
The first step is to register your Vue.js application with Microsoft Entra ID. This registration process creates the necessary credentials (client ID and client secret) and allows you to configure the redirect URIs for your authentication flows.
Registration Process
To register your application, follow these steps:
- Log into the Azure Portal: Navigate to Microsoft Entra ID Portal and sign in with your Azure credentials.
- Access "App registrations": Click on the "Azure Active Directory" section then navigate to "App registrations" or search for it directly.
-
Create a New Application: Select "New registration", provide a name for your application, choose the appropriate supported account types, and set the redirect URI. Typically, this URI points to a specific route in your Vue application (for example,
http://localhost:8080/callback). - Finalize Registration: Click on "Register" to complete the process.
Once registered, note your Application (client) ID and Tenant ID. These will be required for configuration in your Vue.js project.
Step 2: Configuring Entra ID OIDC Settings
Setting Up Redirect URIs and Implicit Grant
With your application registered, configure the authentication settings to properly handle OIDC flows:
Configuration Details
-
Redirect URI: Under "Authentication", set the redirect URI to the endpoint in your Vue application that will process the authentication callback (e.g.,
http://localhost:8080/callback). - Implicit and PKCE Settings: For enhanced security, implement Authorization Code Flow with Proof Key for Code Exchange (PKCE), especially useful for Single Page Applications (SPAs) like those built with Vue.js.
- Client Secret Creation: Navigate to "Certificates & secrets" to generate a new client secret if your application scenario requires it.
These settings ensure that when users authenticate, Entra ID will properly redirect back to your Vue application with the authentication tokens.
Step 3: Integrating OIDC in Your Vue.js Application
Installing and Configuring the OIDC Client Library
The next phase is implementing the OIDC login within your Vue.js application. A common approach is to use an OIDC-compliant client library such as oidc-client. This library streamlines handling the OIDC flow including initiating authentication, handling redirects, and managing tokens.
Library Installation
Install the library using npm:
// Install oidc-client for your project
npm install oidc-client
Once installed, set up a service file to initialize the OIDC client with your application configuration details.
OIDC Client Setup Example
Below is a sample configuration for OIDC in a Vue.js project:
// Import UserManager from oidc-client
import { UserManager, WebStorageStateStore } from 'oidc-client';
// Configuration parameters
const clientId = 'your_client_id';
const tenantId = 'your_tenant_id';
const authority = `https://login.microsoftonline.com/${tenantId}`;
const redirectUri = 'http://localhost:8080/callback';
const responseType = 'code';
const scope = 'openid profile email';
// Initialize the UserManager with a secure state store
const userManager = new UserManager({
authority,
client_id: clientId,
redirect_uri: redirectUri,
response_type: responseType,
scope,
stateStore: new WebStorageStateStore({ store: window.localStorage }),
});
// Export functions to handle login and callback
export const login = () => userManager.signinRedirect();
export const handleCallback = () => userManager.signinRedirectCallback();
Step 4: Implementing the Login Flow in Vue Components
Integrating Authentication into the Vue Lifecycle
In your Vue application, trigger the OIDC flow through user interactions. For example, clicking a "Login" button can initiate the authentication process.
Example: Main App Initialization
The following is an example of how to integrate the login initiation within your main Vue.js file:
// main.js
import Vue from 'vue';
import App from './App.vue';
import { login } from './authService'; // import your OIDC service
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
mounted() {
// Trigger login on app load for demonstration purposes.
this.$nextTick(() => {
login().then(() => {
console.log('Redirecting to login...');
}).catch(error => {
console.error('Login initiation error:', error);
});
});
},
}).$mount('#app');
Additionally, create a dedicated component or route to handle the authentication callback.
Example: Handling the Authentication Callback
// callback.js
import { handleCallback } from './authService';
export default {
mounted() {
// Process OIDC callback after user authentication
this.$nextTick(() => {
handleCallback().then(user => {
console.log('User authenticated:', user);
// Redirect to a secure route, for example:
this.$router.push('/dashboard');
}).catch(error => {
console.error('Error handling callback:', error);
});
});
},
};
Step 5: Protecting Routes with OIDC Authentication
Implementing Route Guards in Vue Router
To secure certain routes in your Vue application, use Vue Router hooks to protect pages that require authentication. Before navigation, confirm that a valid user session exists.
Route Guard Example
Implement a route guard to enforce authentication:
// router.js
import Vue from 'vue';
import Router from 'vue-router';
import { UserManager } from 'oidc-client';
import ProtectedComponent from './components/ProtectedComponent.vue';
Vue.use(Router);
const config = {
authority: 'https://login.microsoftonline.com/your_tenant_id',
client_id: 'your_client_id',
redirect_uri: 'http://localhost:8080/callback',
response_type: 'code',
scope: 'openid profile email',
};
const userManager = new UserManager(config);
const router = new Router({
routes: [
{
path: '/dashboard',
component: ProtectedComponent,
meta: { requiresAuth: true },
},
// additional routes...
],
});
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
userManager.getUser().then(user => {
if (!user) {
next('/login'); // redirect if no valid session exists
} else {
next();
}
}).catch(error => {
console.error('Route guard error:', error);
next('/login');
});
} else {
next();
}
});
export default router;
Comprehensive Configuration Table
| Configuration Item | Details |
|---|---|
| Entra ID Endpoint | https://login.microsoftonline.com/{tenantId} |
| Client ID | Obtained from Azure App Registration |
| Redirect URI | http://localhost:8080/callback (adjust as needed) |
| Response Type | code (Authorization Code Flow with PKCE) |
| Scope | openid profile email |
Additional Best Practices and Tips
Security Considerations
When integrating OIDC with Vue and Entra ID, consider the following security practices:
- Always enforce HTTPS in production environments to protect sensitive tokens.
- Use Authorization Code Flow with PKCE to mitigate interception risks, particularly in SPAs.
- Store authentication tokens securely, for instance using HTTP-only cookies or secure storage mechanisms.
- Regularly update dependencies and review security advisories from both Microsoft and the library maintainers.
User Experience Enhancements
Besides technical configuration, consider improving the user experience:
- Provide clear visual cues during redirection and token fetching.
- Implement graceful error handling with user-friendly messages if authentication fails.
- Ensure that logouts clear both local application storage and invalidate the session on Entra ID.
References
- How-to Custom OIDC Federation - Microsoft Entra Docs
- Microsoft Entra ID OIDC SSO with Vue - Logto Tutorials
- OIDC Web Authentication Configuration - Microsoft Learn
- Vue.js User Authentication with Azure SDKs - Microsoft Dev Blogs
- Securing a Vue.js App with OIDC Code Flow - Damien Bod
Recommended Further Reading
Last updated March 21, 2025