我正在尝试发出一个简单的请求,以使用Microsoft图形OAuth端点获取访问令牌。当我发送下面的简单请求时,我得到
请求的资源上不存在"访问控制允许源"标头。因此,不允许访问源'localhost:8080/myapprunninglocal'。
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://login.microsoftonline.com/common/oauth2/authorize?client_id=<client_id>&scope=wl.signin%20wl.calendars_update&response_type=token&redirect_uri=localhost:8080/myapprunninglocally", true);
xhttp.send();
我还使用 Azure 目录注册了此应用程序Microsoft请求了所有权限,并使用了委派client_id
。
我已经阅读了 CORS,我知道跨源策略,但是,我知道有些 API 会公开在其响应标头中包含'Access-Control-Allow-Origin'
的端点。有人能帮忙吗?
您将无法从客户端运行它。部分 CORS 设置要求 microsoftonline.com 将您的域添加到其支持的 CORS 白名单中。
我建议您在服务器上调用服务,然后使请求服务器到服务器。
要将AAD集成到javascript中,我们建议您使用azure-activedirectory-library-for-js,这是javascript中的前端库,可以轻松集成AAD。
在将 ADAL 用于 JS 之前,我们需要注意 2 个选项:
- 根据 https://github.com/OfficeDev/O365-jQuery-CORS#step-6--run-the-sample 处的节点:
注意:此示例在 Internet Explorer 中不起作用。请使用其他浏览器,例如谷歌浏览器。ADAL.js使用 iframe 获取 SPA 自己的后端以外的资源的 CORS API 令牌。这些 iframe 请求需要访问浏览器的 Cookie 才能使用 Azure Active Directory 进行身份验证。不幸的是,当应用程序在本地主机中运行时,Internet Explorer 无法访问 Cookie。
- 启用 Azure AD 应用程序的
oauth2AllowImplicitFlow
。有关详细步骤,请参阅 https://crmdynamicsblog.wordpress.com/2016/03/17/response-type-token-is-not-enabled-for-the-application-2/。
下面是从 Microsoft Graph 获取访问令牌的代码示例:
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.14/js/adal.min.js"></script>
<body>
<a href="#" onclick="login();">login</a>
<a href="#" onclick="getToken()">access token</a>
</body>
<script type="text/javascript">
var configOptions = {
tenant: "<tenant_id>", // Optional by default, it sends common
clientId: "<client_id>",
postLogoutRedirectUri: window.location.origin,
}
window.authContext = new AuthenticationContext(configOptions);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
function getToken(){
authContext.acquireToken("https://graph.microsoft.com",function(error, token){
console.log(error);
console.log(token);
})
}
function login(){
authContext.login();
}
</script>