问题描述
我正在尝试在我的 React 应用程序中使用 adal-node 实现客户端凭据流
我正在尝试的代码
var AuthenticationContext = require('adal-node').AuthenticationContext;
const authenticate = (): any =>{
var authorityHostUrl = 'https://login.microsoftonline.com';
var tenant = 'xxxx.onmicrosoft.com';
var authorityUrl = authorityHostUrl + '/' + tenant;
var applicationId = '2sdsdwewe-232jkdksdsdsadfsfdsdf';
var clientSecret = 'sdfer245dwfsfw3rt345r342fwfwefwf';
var resource = 'api://sdfwerwerwrwerwerwrewrwer';
var context = new AuthenticationContext(authorityUrl);
context.acquiretokenWithClientCredentials(resource,applicationId,clientSecret,(err: { stack: string; },tokenResponse: any)=> {
if (err) {
console.log('well that didn\'t work: ' + err.stack);
} else {
console.log(tokenResponse);
}
});
}
我从我的本地运行,它是 http://localhost:3000/
因此,在应用程序的 Azure 活动目录应用程序注册中,我在 Web 重定向 URI 下添加了 http://localhost:3000/
。也尝试在 SPA 下添加它
但是当我运行它时会出现 CORS 错误
Access to fetch at 'https://login.microsoftonline.com/xxxx.onmicrosoft.com/oauth2/token?api-version=1.0' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我在这里遗漏了一些东西
当我以 chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
身份运行 Chrome 时
这有效并生成有效的令牌
解决方法
您可以查看此 document 以了解 adal 和 msal 之间的差异。如果您决定使用 msal.js 通过 azure ad 集成身份验证,则不能使用客户端凭据流,因为此流用于 Daemon application。
我可以为您提供一个 sample,它使用 msal.js 在 spa 中使用隐式授权流,希望它可以帮助您,我将继续在 adal 上找到解决方案。
并按照您提供的相关链接,我下载了此 sample,然后 发现我在vs code中打开示例代码并修改'client-credentials-sample.js'、npm模块和'node sample\client-credentials-sample.js'中的配置后,可以成功得到响应,所以我无法重现您的问题。我没有添加重定向网址。
另一方面,如果你想解决 cors 问题,你应该编辑你的 api 程序而不是这个,同一个域不同的端口也会导致跨域。我创建了一个 java api 应用程序,我使用过滤器来解决核心问题。而且我是 node 的新手,所以我不确定 it 是否可以帮助解决 nodejs 中的 cors。
Timer timer;
Timer.periodic(Duration(seconds: 10),(Timer t) async {
timer = t;
print("loop operation");
});
//inside a button callback
timer??.cancel(); // perform null check as well before cancelling.