如何使用 Azure AD 对 VueJS 应用程序进行身份验证?

编程入门 行业动态 更新时间:2024-10-27 18:28:31
本文介绍了如何使用 Azure AD 对 VueJS 应用程序进行身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm setting up an app using the VueJS 2.x framework and it needs to authenticate users via the Azure Active Directory service. I already have "login info" (Auth and Token URLs) neccessary for the service.

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

So far, I've only encountered one article that shows the setup in VueJS, but it relies on a third party service (Auth0) - adding uneccessary convolution in the process.

当 没有任何 VueJS npm 模块 允许轻松进行身份验证?或者您是否必须依赖 Vue 之外的库,例如 Adal JS?

How do you proceed when there aren't any VueJS npm modules that allow for doing authenticating easily? Or do you have to rely on a library outside of Vue like Adal JS?

任何建议都会有所帮助.

Any suggestions would be helpful.

推荐答案

为了解决这个问题,我依靠 ADAL JS.我在 这里 提供了一个 Vue + Vue-Router 示例应用程序a> - 但我会在下面列出重要的部分.

To solve this very problem, I leaned on ADAL JS. I've made a Vue + Vue-Router sample application available here - but I'll include the important pieces below.

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

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

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

Add access token to request headers

The below is an example of a vue-resource http interceptor, but any method will do.

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

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

Hopefully this saves somebody a little time :)

更多推荐

如何使用 Azure AD 对 VueJS 应用程序进行身份验证?

本文发布于:2023-11-12 19:16:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582301.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   应用程序   身份验证   AD   Azure

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!