无法从浏览器(SPA)获取OAuth2访问令牌

时间:2019-06-19 06:23:17

标签: oauth-2.0 cors wso2

我正在使用JS客户端来演示单页应用程序(SPA)的OAuth工作流程。我正在使用WSO2作为身份验证服务器。

用户通过登录和同意页面后,客户端(浏览器)可以获得身份验证代码。但是,当它尝试使用下面的ajax代码请求令牌时,它就卡住了。

我的ajax(main.html):

// process the auth code
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}


if (getParameterByName('code')) {

    var auth_code = getParameterByName('code');
    var token_endpoint = "https://authserver:9443/oauth2/token";
    var callback_uri = "http://spa/main.html#callback";

    $.ajax({
        url: token_endpoint,
        headers: {
            "Authorization":"Basic MWhWRmhRMDdUU1dnS3RNWHlDbjhLeVNNY1BzYTp0UnVaVHlkU01lM3oyeVRpZFNob29XSFo2c2th",
            "Content-Type":"application/x-www-form-urlencoded"
        },
        method: "POST",
        dataType: "text",
        data: 
        {
            grant_type: "authorization_code",
            code: auth_code,
            redirect_uri: callback_uri
        },
        success: function(data){
          console.log("success: "+data);
          alert("ajax success");
        },
        error: function(jqXHR, textStatus, errorThrown) { 
            alert("ajax error!");
            alert(jqXHR.responseText);
        }   
      });
}

提示提示:1)ajax错误! 2)未定义

我检查了以下Chrome开发工具信息:

常规

Request URL: https://authserver:9443/oauth2/token
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 10.27.134.142:9443
Referrer Policy: no-referrer-when-downgrade

响应标题

Allow: POST,OPTIONS
Content-Length: 0
Date: Wed, 19 Jun 2019 03:51:54 GMT
Server: WSO2 Carbon Server
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

请求标头

Access-Control-Request-Headers: authorization
Access-Control-Request-Method: POST
Origin: http://spa
Referer: http://spa/main.html

首先,我怀疑CORS是否有问题。 我检查了WSO2服务器已在全局启用CORS。 有人可以指出我出了什么问题吗?非常感谢!

0 个答案:

没有答案
相关问题