没有 'Access-Control-Allow-Origin' header Microsoft Online Auth

No 'Access-Control-Allow-Origin' header with Microsoft Online Auth

我正在尝试使用 Microsoft 图形 OAuth 端点发出一个简单的请求来获取访问令牌。当我发送下面的简单请求时,我得到

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8080/myapprunninglocally' is therefore not allowed access.**"

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();

我还使用 Microsoft Azure Directory 注册了此应用程序,请求了所有权限,并使用了委托 client_id

我已经阅读了 CORS 并且我知道 Cross-Origin 政策但是,我知道有一些 API 公开端点,这些端点在其响应 headers 中包含 'Access-Control-Allow-Origin'。有人能帮忙吗?

您将无法 运行 来自客户端的。部分 CORS 设置要求 microsoftonline.com 将您的域添加到他们支持 CORS 的白名单中。

我建议你在你的服务器上调用一个服务,然后请求服务器到服务器。

要在 javascript 中集成 AAD,我们建议您使用 azure-activedirectory-library-for-js,它是 javascript 中的一个前端库,可以轻松集成 AAD。

在使用 ADAL for JS 之前,我们需要注意两个选项:

这是从 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>