[](https://www.npmjs.com/package/@wra-gov/vue-msal)
npm install @wra-gov/vue-msal
Vue wrapper around Microsoft's MSAL.js for browser library
You can install the library,
``bash`
npm install @wra-gov/vue-msal --save
To use msal, a msal instance must be created. Msal instances have need an auth configuration. The user must provide this auth configuration.
The auth and cache objects are important. Objects in system help with debugging and are not required.
`ts
import { LogLevel, PublicClientApplication } from "@azure/msal-browser";
// Config object to be passed to Msal on creation
export const msalConfig = {
auth: {
clientId: "", // Fill in
authority: "", // Fill in
redirectUri: "/", // Must be registered as a SPA redirectURI on your app registration
postLogoutRedirectUri: "/" // Must be registered as a SPA redirectURI on your app registration
},
cache: {
cacheLocation: "localStorage"
},
system: {
loggerOptions: {
loggerCallback: (
level: LogLevel,
message: string,
containsPii: boolean
) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
default:
return;
}
},
logLevel: LogLevel.Verbose
}
}
};
export const msalInstance = new PublicClientApplication(msalConfig);
`
The instance must be registered in index.js / index.ts. The plugin must always be the first thing initialised; all other things must happen after msal has finished initialisation.
To use control routing, the VueNavigationClient must be registered to the application's router,
`ts`
const navigationClient = new VueNavigationClient(router);
msalInstance.setNavigationClient(navigationClient);
msal should be initialised in a promise,
`ts
msalInstance.initialize().then(() => {
// This is a standard account configuration. Account configs can vary with
// what the application requires.
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
msalInstance.setActiveAccount(accounts[0]);
}
msalInstance.addEventCallback((event) => {
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
const payload = event.payload as AuthenticationResult;
const account = payload.account;
msalInstance.setActiveAccount(account);
}
});
const app = createApp(App);
app.use(router);
// The msal plugin is registered with the msalInstance
app.use(msalPlugin, msalInstance);
app.use(Wra);
router.isReady().then(() => {
// Waiting for the router to be ready prevents race conditions when returning from a loginRedirect or acquireTokenRedirect
app.mount("#app");
});
});
`
@wra-gov/vue-msal uses the meta object for route authorisation.
Guarded routes should have meta.requiresAuth set to true,
`ts`
const routes: Array
{
path: "/",
name: "Home",
component: Home
},
{
path: "/profile",
name: "Profile",
component: Profile,
meta: {
requiresAuth: true
}
},
{
path: "/profileNoGuard",
name: "ProfileNoGuard",
component: ProfileNoGuard
},
{
path: "/failed",
name: "Failed",
component: Failed
}
];
After the routes are created, the registerGuard function should be called,
`ts
// Example router
const router = createRouter({
history: createWebHistory(),
routes
});
registerGuard(router, msalInstance, loginRequest);
export default router;
`
There are 3 composables,
- useIsAuthenticatedboolean
- Checks if the user is part of the Entra ID tentant.
- Returns a .useMsal
- s account details and a msal instance to use.
- Provides the user
- Asynchronous composable, requires checking a inProgress ref.
- useMsalAuthentication
- Accepts a scope parameter.
- Accepts a authentication method. Either,
- Redirect based - this is the WRAs recommended way as it supports test engines.s account details, and a token for the requested scope.
- Popup based - not recommended as it requires users to assign permissions and casuses issues with test engines.
- Provides the user
- Asynchronous composable, requires checking a inProgress ref.
#### useIsAuthenticated
`` You are signed in.vue
Please sign-in to see your profile information.
`
#### useMsal
Accessing account information using useMsal,
`vue
Name: {{ name }}
`
---
Using the msal instance for sign in and sign out functionality,
loginRequest is an object containing the scopes for the login,
`ts`
// Add scopes that are requested for id token provided by MS Identity Platform.
export const loginRequest = {
scopes: ["User.Read"]
};
`vue
`
---
Using the msal instance through useMsal to get access tokens.
> I would recommend using useMsalAuthentication over this,
loginRequest is an object containing the scopes for the graph query,
`ts`
// Add scopes that are requested for id token provided by MS Identity Platform.
export const loginRequest = {
scopes: ["User.Read"]
};
graphConfig is an object that contains the graph URLs,
`ts`
// Add here the endpoints for MS Graph API services you would like to use.
export const graphConfig = {
graphMeEndpoint: "https://graph.microsoft.com/v1.0/me"
};
` Name: {{ state.data.displayName }} Title: {{ state.data.jobTitle }} Mail: {{ state.data.mail }} Location: {{ state.data.officeLocation }} Getting statevue
Phone: {{ state.data.businessPhones ? state.data.businessPhones[0] : "" }}
`
#### useMsalAuthentication
To use the useMsalAuthentication, an interaction type and scope must be passed in.
Interaction types:
- InteractionType.PopupInteractionType.Redirect
-
`ts`
// Add scopes that are requested for id token provided by MS Identity Platform.
export const loginRequest = {
scopes: ["User.Read"]
};
graphConfig is an object that contains the graph URLs,
`ts`
// Add here the endpoints for MS Graph API services you would like to use.
export const graphConfig = {
graphMeEndpoint: "https://graph.microsoft.com/v1.0/me"
};
` Name: {{ state.data.displayName }} Title: {{ state.data.jobTitle }} Mail: {{ state.data.mail }} Location: {{ state.data.officeLocation }}vue
Phone: {{ state.data.businessPhones ? state.data.businessPhones[0] : "" }}
`
All of the composables listed above can be used in options API. However, they have to be placed into a setup method. The setup method places it's returns into the data() method automatically.
` Name: {{ state.data.displayName }} Title: {{ state.data.jobTitle }} Mail: {{ state.data.mail }} Location: {{ state.data.officeLocation }}vue
Phone: {{ state.data.businessPhones ? state.data.businessPhones[0] : "" }}
`
The test folder contains an sample project, containing a typical WRA project structure with Tailwind and the WRA component library.
- main.ts setups up the MSAL pluginsauthConfig.ts
- provides the PublicClientApplication that is used by main.ts to setup configuration and hooks.router/router.ts
- sets up role guards.
To run the sample / tests, you must navigate into the test folder. The top level of the repo is for the plugin, not the sample.
`bash``
cd test
npm install
npm run dev