node.js - 如何使用 Azure AD 验证 VueJS 应用程序?

标签 node.js azure vue.js vuejs2 azure-active-directory

我正在使用 VueJS 2.x 框架设置一个应用程序,它需要通过 Azure Active Directory 服务对用户进行身份验证。我已经拥有该服务所需的“登录信息”(身份验证和 token URL)。

到目前为止,我只遇到过 one article显示了 VueJS 中的设置,但它依赖于第三方服务 (Auth0) - 在过程中添加不必要的卷积。

出现 aren't any VueJS npm modules 时您如何进行?可以轻松进行身份验证吗?或者你是否必须依赖 Vue 之外的库,例如 Adal JS

任何建议都会有帮助。

最佳答案

为了解决这个问题,我依靠了 ADAL JS。我已经制作了一个 Vue + Vue-Router 示例应用程序 here - 但我将在下面包含重要的部分。

在你的package.json中:

"dependencies": {
    "adal-angular": "^1.0.15",
    "vue": "^2.5.2",
    "vue-router": "^3.0.1"
},

ADAL JS 库的基本包装模块:

import AuthenticationContext from 'adal-angular/lib/adal.js'

const config = {
  tenant: 'your aad tenant',
  clientId: 'your aad application client id',
  redirectUri: 'base uri for this application',
  cacheLocation: 'localStorage'
};

export default {
  authenticationContext: null,
  /**
   * @return {Promise}
   */
  initialize() {
    this.authenticationContext = new AuthenticationContext(config);

    return new Promise((resolve, reject) => {
      if (this.authenticationContext.isCallback(window.location.hash) || window.self !== window.top) {
        // redirect to the location specified in the url params.
        this.authenticationContext.handleWindowCallback();
      }
      else {
        // try pull the user out of local storage
        let user = this.authenticationContext.getCachedUser();

        if (user) {
          resolve();
        }
        else {
          // no user at all - go sign in.
          this.signIn();
        }
      }
    });
  },
  /**
   * @return {Promise.<String>} A promise that resolves to an ADAL token for resource access
   */
  acquireToken() {
    return new Promise((resolve, reject) => {
      this.authenticationContext.acquireToken('<azure active directory resource id>', (error, token) => {
        if (error || !token) {
          return reject(error);
        } else {
          return resolve(token);
        }
      });
    });
  },
  /**
   * Issue an interactive authentication request for the current user and the api resource.
   */
  acquireTokenRedirect() {
    this.authenticationContext.acquireTokenRedirect('<azure active directory resource id>');
  },
  /**
   * @return {Boolean} Indicates if there is a valid, non-expired access token present in localStorage.
   */
  isAuthenticated() {
    // getCachedToken will only return a valid, non-expired token.
    if (this.authenticationContext.getCachedToken(config.clientId)) { return true; }
    return false;
  },
  /**
   * @return An ADAL user profile object.
   */
  getUserProfile() {
    return this.authenticationContext.getCachedUser().profile;
  },
  signIn() {
    this.authenticationContext.login();
  },
  signOut() {
    this.authenticationContext.logOut();
  }
}

在应用程序的入口点(如果您使用 vue-cli,则为 main.js):

import Vue from 'vue'
import App from './App'
import router from './router'
import authentication from './authentication'

// Init adal authentication - then create Vue app.
authentication.initialize().then(_ => {
  /* eslint-disable no-new */
  new Vue({
    el: '#app',
    router,
    template: '<App/>',
    components: { App }
  });
});

对于您的 Vue 路由器配置:

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import authentication from '../authentication'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld,
      meta: {
        requiresAuthentication: true
      }
    }
  ]
})

// Global route guard
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuthentication)) {
    // this route requires auth, check if logged in
    if (authentication.isAuthenticated()) {
      // only proceed if authenticated.
      next();
    } else {
      authentication.signIn();
    }
  } else {
    next();
  }
});

export default router;

在你的 Vue 组件中:

import authentication from './authentication'
...
computed: {
  isAuthenticated() {
    return authentication.isAuthenticated();
  }
},
methods: {
  logOut() {
    authentication.signOut();
  }
}

将访问 token 添加到请求 header

下面是 vue-resource http 拦截器的示例,但任何方法都可以。

Vue.http.interceptors.push(function (request, next) {
  auth.acquireToken().then(token => {
    // Set default request headers for every request
    request.headers.set('Content-Type', 'application/json');
    request.headers.set('Ocp-Apim-Subscription-Key', 'api key');
    request.headers.set('Authorization', 'Bearer ' + token)
    // continue to next interceptor
    next();
  });
});

希望这可以节省一些人的时间:)

关于node.js - 如何使用 Azure AD 验证 VueJS 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44437634/

相关文章:

javascript - 更新到 Angular 5

python - Streamlit azure 部署请稍候屏幕错误

javascript - 使用 javascript/vue 按最高和最低产品过滤器排序

javascript - Vue.js v-for item,将属性绑定(bind)到当前索引/键

node.js - 我可以将命令与 Node.js 的 gm 链接在一起吗?

node.js - Laravel-mix - BrowserSync 在 event.js :160 处抛出错误

node.js - 当 cron 在后台运行时,没有 Mongo 查询得到结果

azure - 一个可以监听所有容器的 Cosmos DB 更改源的 Azure 函数

asp.net-mvc-4 - Azure - 使用 ADFS 在 Azure 中运行应用程序返回以下错误 : Exception message: ID4014: A SecurityTokenHandler is not

css - 如何为具有不同屏幕尺寸的所需输出安排行和列 :