Riy*_*nat 4 javascript cors microsoft-graph-api
我正在尝试使用 Microsoft 图形 OAuth 端点发出一个简单的请求来获取访问令牌。当我发送下面的简单请求时,我得到
请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问源 'localhost:8080/myapprunninglocally'。**"
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();
Run Code Online (Sandbox Code Playgroud)
我还使用 Microsoft Azure Directory 注册了此应用程序,请求了所有权限,并使用了委派的client_id.
我已经阅读了 CORS 并且我知道跨域策略,但是我知道有一些 API 公开了包含'Access-Control-Allow-Origin'在响应头中的端点。有人可以帮忙吗?
小智 5
您将无法从客户端运行它。CORS 设置的一部分要求 microsoftonline.com 将您的域添加到其支持 CORS 的白名单。
我建议你在你的服务器上调用一个服务,然后让请求服务器到服务器。
要将 AAD 集成到 javascript 中,我们建议您使用azure-activedirectory-library-for-js,这是一个 javascript 中的库,用于前端轻松集成 AAD。
在使用 ADAL for JS 之前,有两个选项需要注意:
注意 此示例无法在 Internet Explorer 中运行。请使用其他浏览器,例如 Google Chrome。ADAL.js 使用 iframe 获取 SPA 自己的后端以外的资源的 CORS API 令牌。这些 iframe 请求需要访问浏览器的 cookie,以便通过 Azure Active Directory 进行身份验证。不幸的是,当应用程序在本地主机中运行时,Internet Explorer 无法访问 cookie。
oauth2AllowImplicitFlowAzure AD 应用程序。有关详细步骤,请参阅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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14083 次 |
| 最近记录: |