npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vue-msal-browser

v2.0.0

Published

Vue plugin to authenticate with the msal-browser library

Downloads

2,778

Readme

Vue-MSAL-Browser

vue-msal-browser is a VueJS 2 wrapper for the msal-browser library. You can use it to authenticate the users of your SPA and retrieve their access token to call your backend APIs.

It is widely inspired by the vue-msal library by @mvertopoulos

Pre-requisites

To use it you need:

Installation

Use npm or yarn to install vue-msal-browser.

npm install vue-msal-browser
or
yarn add vue-msal-browser

Usage

Vue CLI

Initialize the plugin

For the Vue apps generated with the Vue CLI, you can import the plugin in the main.js file like described below.
The options allowed are the same as the options of the MSAL browser library.

import { default as msalPlugin } from "vue-msal-browser";
const msalConfig = {
  auth: {
    tenant: '<your-tenant>',
    clientId: '<your-client-id>',
    authority: '<your-tenant-address>',
    redirectUri: '<your-redirect-url>', // It has to be configured on your Azure tenant
    scopes: ['<your-scopes>']
  },
  cache: {
    cacheLocation: '<your-cache-location>'
  },
  graph: {
    url: '<your-graph-api-url>',
    scopes: '<your-graph-api-scopes>',
    response_type: "blob"
  },
  mode: "redirect"
  ...
}
Vue.use(msalPlugin, msalConfig);

Use the plugin from a view component

You can call the plugin from you Vue components like a Vue.prototype


<template>
    <a href="#" v-if="accounts !== 0" @click="logout()">Logout</a>
</template>

<script>
export default {
  methods: {
    logout: function () {
      this.$msal.logoutRedirect()
    }
  },
  created () {
    this.$msal.authenticateRedirect()
  }
}

</script>

Use the plugin in the VueX store

You can also call it from the actions, mutation or getters in your Vue store.
First import the msalInstance

import { msalInstance } from "vue-msal-browser"

And then call the plugin in your actions

export default {
  async AzureAuthentication() {
    msalInstance.authenticateRedirect();
  },
};

Here is a more detailed example: The following action authentify the users on redirect mode with a cachelocation "localStorage".

export default {
  // Authenticate the user with Active Directory
  async AzureAuthentication({ commit, getters, dispatch }) {
    try {
      let existingTokenResponse = getters.mainTokenResponse;
      let newTokenResponse;

      // The user has already logged in. We try to get his token silently
      if (existingTokenResponse)
        newTokenResponse = await msalInstance.acquireTokenSilent({
          account: existingTokenResponse.account,
          scopes: msalInstance.extendedConfiguration.auth.scopes,
        });
      // The user has not logged in. We check if he comes back from a redirect with a token
      else newTokenResponse = await msalInstance.handleRedirectPromise();

      // No token found, we redirect the user
      if (!newTokenResponse) {
        await msalInstance.loginRedirect(msalInstance.loginRequest);
        return false;
      }
      // There is an existing token, we authentify the user
      else if (newTokenResponse) {
        // We add the access token as an authorization header for our Axios requests to our API
        this._vm.axios.defaults.headers.common["Authorization"] =
          "Bearer " + newTokenResponse.accessToken;
        if (msalInstance.extendedConfiguration.graph) {
          // The graph is set, we check if the user has already a picture in the local storage
          // if he does not we grab a token silently for our graph scope and call Microsoft graph to get the picture
          if (!localStorage.getItem("userPicture")) {
            let graphTokenResponse = await msalInstance.getSilentToken(
              newTokenResponse.account,
              msalInstance.extendedConfiguration.graph.scopes
            );
            let graphResponse = await msalInstance.callMSGraph(
              msalInstance.extendedConfiguration.graph.url,
              graphTokenResponse.accessToken
            );
            dispatch("AzureSetPicture", graphResponse);
          }
        }
        return true;
      }
    } catch (error) {
      console.error(error);
    }
  },
};

Extra configuration options and methods

The chapter below describes the extra configuration options and methods added by vue-msal-browser. For more information about how to use the basic msal-browser functions, please refer to the MSAL browser documentation.

Extra configuration options

General Config Options

| Option | Description | Format | Default Value | | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------ | ------------- | | mode | MSAL Interaction type used for authentication. Used in the authenticate method. Can be redirect or popup | string | undefined |

Auth Config Options

| Option | Description | Format | Default Value | | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ------------- | | scopes | Default authentication scopes that your users will be allowed to access. | Array of strings | [] |

Graph Config Options

| Option | Description | Format | Default Value | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------- | ------------- | | url | The URL of your graph API. | string | undefined | | scopes | Default authentication scopes that your users require from you graph API. | Array of strings | [] | | response_type | Response type expected from the graph API. | string | undefined |

Extra methods

The following methods have been added to the msal-browser original methods

1. authenticate

  • Usage: Authenticate the user with a redirect or a popup depending on the mode configuration option.

  • Example: msalInstance.authenticate()

2. authenticateRedirect

  • Usage: Ensure that there is no interaction ongoing and authenticate the user with the redirect mode if he is not authenticated yet.

  • Example: msalInstance.authenticateRedirect()

3. authenticatePopup

  • Usage: Authenticate the user with the popup mode if he is not authenticated yet.

  • Example: msalInstance.authenticatePopup()

4. getSilentToken

| Parameter name | Type | Description | | -------------- | ---------------- | ------------------------ | | account | Object | MSAL user account object | | scopes | Array of strings | Graph scopes |

  • Usage:
    Grab a token silently for a given user and scope and return an access token object as a response. Redirect the user to the login if it fails.

  • Example:
    let graphTokenResponse = await msalInstance.getSilentToken(newTokenResponse.account, msalInstance.extendedConfiguration.graph.scopes);

5. callMSGraph

| Parameter name | Type | Description | | -------------- | ------ | ------------------------ | | endpoint | String | Microsoft graph endpoint | | accessToken | String | Azure access token |

  • Usage: Allows to use the access token retrieved by the main msalInstance to call MSGraph

  • Example: let graphResponse = await msalInstance.callMSGraph(msalInstance.extendedConfiguration.graph.url, graphTokenResponse.accessToken);

Todos

  • Make a Vue 3 version
  • Add the mode as a parameter to the getSilentToken method
  • Add tests
  • [README] Add infos on Nuxt usage

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

License

MIT