如何使用Azure ADvalidationVueJS应用程序?

我正在使用VueJS 2.x框架设置应用程序,并需要通过Azure Active Directory服务对用户进行身份validation。 我已经有了“login信息”(Auth和Token URLs)这个服务。

到目前为止,我只遇到一篇文章 ,显示VueJS中的设置,但它依赖于第三方服务(Auth0) – 在此过程中增加了不必要的卷积。

当没有任何VueJS npm模块可以轻松进行身份validation时,如何继续? 还是必须依赖Adal JS之类的Vue之外的图书馆?

任何的意见都将会有帮助。

Solutions Collecting From Web of "如何使用Azure ADvalidationVueJS应用程序?"

为了解决这个问题,我倾向于ADAL JS 。 我已经在这里提供了一个Vue + Vue-Router示例应用程序 – 但是我将在下面包含重要的内容。

在你的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, userProfilePromise: null, /** * @return {Promise} */ initialize() { this.authenticationContext = new AuthenticationContext(config); return new Promise((resolve, reject) => { if (this.authenticationContext.isCallback(window.location.hash) || window !== window.parent) { // redirect to the location specified in the url params. this.authenticationContext.handleWindowCallback(); } else { var user = this.authenticationContext.getCachedUser(); if (user && window.parent === window && !window.opener) { // great, we have a user. } else { // no user, kick off the sign in flow. this.signIn(); } resolve(); } }); }, /** * @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 {Promise.<Object>} An ADAL user profile object. */ getUserProfile() { if (!this.userProfilePromise) { this.userProfilePromise = this.initialize().then(() => { return this.authenticationContext.getCachedUser().profile; }); } return this.userProfilePromise; }, signIn() { this.authenticationContext.login(); }, signOut() { this.authenticationContext.logOut(); } } 

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

 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路由器configuration:

 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(); } } 

将访问令牌添加到请求标头

下面是一个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(); }); }); 

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

保护客户端数据的概念是在必要时总是检查authentication信息。

不知道有一个库来帮助VueJs应用程序的安全。 但是,我们可以轻松地利用Adal js进行身份validation。

我还写了一个简单的演示供您参考:

Index.html

  <html> <head> <script src="https://unpkg.com/vue"></script> <script src="node_modules\adal-angular\lib\adal.js"> </script> <script src="config.js"> </script> <script> var authContext=new AuthenticationContext(config); function login(){ authContext.login(); } function init(configOptions){ if (configOptions) { // redirect and logout_redirect are set to current location by default var existingHash = window.location.hash; var pathDefault = window.location.href; if (existingHash) { pathDefault = pathDefault.replace(existingHash, ''); } configOptions.redirectUri = configOptions.redirectUri || pathDefault; configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault; // create instance with given config } else { throw new Error('You must set configOptions, when calling init'); } // loginresource is used to set authenticated status updateDataFromCache(authContext.config.loginResource); } var _oauthData = { isAuthenticated: false, userName: '', loginError: '', profile: '' }; var updateDataFromCache = function (resource) { // only cache lookup here to not interrupt with events var token = authContext.getCachedToken(resource); _oauthData.isAuthenticated = token !== null && token.length > 0; var user = authContext.getCachedUser() || { userName: '' }; _oauthData.userName = user.userName; _oauthData.profile = user.profile; _oauthData.loginError = authContext.getLoginError(); }; function saveTokenFromHash(){ var hash = window.location.hash; var requestInfo = authContext.getRequestInfo(hash); if (authContext.isCallback(hash)) { // callback can come from login or iframe request var requestInfo = authContext.getRequestInfo(hash); authContext.saveTokenFromHash(requestInfo); window.location.hash = ''; if (requestInfo.requestType !== authContext.REQUEST_TYPE.LOGIN) { authContext.callback = window.parent.AuthenticationContext().callback; } } } function isAuthenticate(){ return _oauthData.isAuthenticated; } saveTokenFromHash(); init(config); </script> </head> <body> <div id="app"> <p v-if="_oauthData.isAuthenticated">Hello {{oauthData.userName}}</p> <button onclick="login()" v-else>Login</button> </div> <script> var app=new Vue({ el: '#app', data: { oauthData:_oauthData, } }) </script> </body> </html>