OAuth2访问源错误

OAuth2 Access origin error

本文关键字:错误 访问 OAuth2      更新时间:2023-09-26

I向OAuth2服务器请求authorization code。我的目的是授权用户使用我的微软应用程序。参考文献

My attempt for get Call:

function httpGet(){
        var theUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id="client_id"&response_type=code&redirect_uri="redirect_uri"&response_mode=query&resource=https%3A%2F%2Fservice.contoso.com%2F&state=12345";
        var req = new XMLHttpRequest();
        req.open('GET', theUrl, true);
        req.onreadystatechange = function() {
            if (req.readyState === 4) {
                if (req.status >= 200 && req.status < 400) {
                    console.log(req.responseText)
                } else {
                    console.log("error")
                }
            }
        };
        req.send();
    }

,但这会产生以下错误:

请求的文件中没有'Access-Control-Allow-Origin'标头资源。

然后加上req.setRequestHeader("Access-Control-Allow-Origin", "*");

,但它给出以下错误:

对预飞行请求的响应未通过访问控制检查:No"访问-控制-允许-起源"标头出现在请求上资源。

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

在为JS使用ADAL之前,我们需要注意两个选项:
  • 根据https://github.com/OfficeDev/O365-jQuery-CORS#step-6--run-the-sample:节点

    注意:这个示例不能在Internet Explorer中工作。请使用其他浏览器,例如Google Chrome。js使用iframe来获取资源的CORS API令牌,而不是SPA自己的后端。这些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.10/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>

不使用任何frontend谷歌库,我想出了解决方案。

window.open("url") 

完成身份验证后,我从url params获得code并将其发送backend并实现access token, refersh token.......etc,