我想对Azure进行身份验证,以声明一个访问令牌,并将其用于Graph。所以我做了我的家庭作业,从这个指南开始
https://learn.microsoft.com/en-us/graph/auth-v2-service
我成功地验证了身份。但是代码的数量很大。这是我为身份验证编写的自己的代码:
如果脚本需要访问当前会话令牌,则只需调用getAuthenticationInfo函数即可。由于大量的代码,我想知道我的代码是多余的,还是不正确。
经过一些研究,我来到了MSAL.js,它(我认为)为我处理身份验证工作。MSAL使用了与我上面发布的链接不同的方法。我从这个简单的JS演示代码开始(我只有一个演示帐户,所以凭据不重要)
const msal = require('msal');
async function start() {
const clientId = 'bec52b71-dc94-4577-9f8d-b8536ed0e73d';
const clientSecret = 'OV/NkBIWH7d3G/BGyJQN3vxQA]fT6qK@';
const tenant = '2c1714e1-1030-4da9-af5e-59630d7fe05f';
const scope = 'https://graph.microsoft.com/.default';
const grantType = 'client_credentials';
const msalConfig = {
auth: {
clientId
}
};
const msalInstance = new msal.UserAgentApplication(msalConfig);
const tokenRequest = {
scope,
};
try {
const tokenResponse = await msalInstance.acquireTokenSilent(tokenRequest);
const { accessToken } = tokenResponse;
console.log(accessToken);
} catch (error) {
throw error;
}
}
start();我在想,我应该把我的登录凭证放在这里。但是,当我运行代码时,我会得到以下错误
ReferenceError:未定义窗口
代码似乎试图访问浏览器存储。但是我的代码正在节点环境中运行。那么,有人愿意告诉我如何从基于MSAL方法的第一个链接的代码片段中传输代码吗?
据我所知,MSAL应该为我做到这一点,我不需要自己编写身份验证代码,并且可以缩短自己的代码。
提前感谢!
更新
基于Allen的答案,我试用了ADAL.js,这段代码似乎运行良好
const { AuthenticationContext } = require('adal-node');
const clientId = 'bec52b71-dc94-4577-9f8d-b8536ed0e73d';
const clientSecret = 'OV/NkBIWH7d3G/BGyJQN3vxQA]fT6qK@';
const tenant = '2c1714e1-1030-4da9-af5e-59630d7fe05f';
const authorityHostUrl = 'https://login.windows.net';
const authorityUrl = `${authorityHostUrl}/${tenant}`;
const resource = 'https://graph.microsoft.com';
const context = new AuthenticationContext(authorityUrl);
context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, (error, tokenResponse) => {
if (error) {
throw error;
}
console.log(tokenResponse);
});我唯一不明白的就是resource是什么。请随意添加一条解释它的评论:)
发布于 2019-12-23 02:33:22
您会得到"ReferenceError: window未定义“错误,因为节点上不存在浏览器内容。
MSAL.js被设计用于在web浏览器中运行的客户端JavaScript,例如单页应用程序。换句话说,它目前不支持nodejs。
对于控制台应用程序,可能需要查看MSAL .Net。
或者你可能对ADAL for nodejs感兴趣。
https://stackoverflow.com/questions/59448046
复制相似问题