我继承了一个用 Angular 编写的项目,并使用正确的配置部署到 Azure DevOps。 我被要求制作这个项目的 2.0 版本,但这次是用 Vue 编写的。 该项目已经完成,并且在本地主机上完美运行(登录拉动 MSAL 等)。问题出在部署它的时候。部署正确,但无法登录。
这是因为它使用了版本中的组变量,Angular 中已经配置了访问它们,但使用 Vue 时我无法做到这一点。 在 Angular 中,项目根目录中有一个名为
env.js
的文件,其中包含以下代码:
(function (window) {
window.__env = window.__env || {};
window.__env.clientID = 'variable-id';
}(this));
然后我看到这个文件被加载到了
src/index.html
<script src="env.js"></script>
在
apply-deploy.yml
我有这个:
args: ["-c", "sed -i -e s/variable-id/#{variable-id}#/g /usr/share/nginx/html/name-of-my-proyect/env.js ;nginx -g 'daemon off;'"]
然后在 MSAL 的配置中,Angular 项目有这样的加载 clientID:
window['__env']['clientID'];
所以,我需要在 Vue.js 中做类似的事情
我尝试过不同的方法,但都不起作用,它总是给我不确定的感觉。 使用相同的配置(使用 env.js)它不起作用。
我尝试在azure版本中使用替换令牌,但也许我不知道如何正确执行它,但它不起作用。
我有像
.env
和 .env.prod
这样的环境文件,并且我有一些常量,例如:VUE_APP_NAME="XXXXX"
,所以我尝试添加这样的内容:
VUE_APP_CLIENT_ID=#{variable-id}#
但这不起作用。我不知道该怎么做。
非常感谢
我尝试在 vue+MSAL
上引用 Sunil Bandla 的
Github 样本,并且我能够通过在我的根项目中创建
ClientID
文件来访问环境变量中的
.env
,如下所示:-
我的源代码文件夹:-
我的
.env
文件:-
clientID=xxxxxxxxxxxxx
我还安装了以下软件包以使 .env 软件包成功工作:-
npm install --save-dev vue-cli-plugin-env
在上面的 Github 示例中的 auth.service.js 中引用并编辑了上面的 clientID,如下所示:-
clientID: process.env.clientID
完整auth.service.js代码:-
import * as Msal from 'msal';
export default class AuthService {
constructor() {
let PROD_REDIRECT_URI = 'https://sunilbandla.github.io/vue-msal-sample/';
let redirectUri = window.location.origin;
if (window.location.hostname !== '127.0.0.1') {
redirectUri = PROD_REDIRECT_URI;
}
this.applicationConfig = {
clientID: process.env.clientID,
graphScopes: ['user.read']
};
this.app = new Msal.UserAgentApplication(
this.applicationConfig.clientID,
'',
() => {
// callback for login redirect
},
{
redirectUri
}
);
}
login() {
return this.app.loginPopup(this.applicationConfig.graphScopes).then(
idToken => {
const user = this.app.getUser();
if (user) {
return user;
} else {
return null;
}
},
() => {
return null;
}
);
};
logout() {
this.app.logout();
};
getToken() {
return this.app.acquireTokenSilent(this.applicationConfig.graphScopes).then(
accessToken => {
return accessToken;
},
error => {
return this.app
.acquireTokenPopup(this.applicationConfig.graphScopes)
.then(
accessToken => {
return accessToken;
},
err => {
console.error(err);
}
);
}
);
};
}
输出:-
我能够成功登录,如下所示:-
在发布管道中不需要添加环境变量,因为我使用 .env 来检索变量:-