【问题标题】:How to get oauth access_token with jQuery (localhost)?如何使用 jQuery (localhost) 获取 oauth access_token?
【发布时间】:2019-11-14 11:00:33
【问题描述】:

我正在尝试使用 jQuery 获取 access_token。问题是,我无法获得该令牌(服务器在 localhost 上运行)。服务器工作正常(我用邮递员试过),但我不能用 jQuery 得到它。 浏览器在点击按钮后写入。

来自“http://localhost:8080/oauth/token?callback=jQuery34105901959820360243_1562175129954&grant_type=password&client_id=my-client&client_secret=my-secret&username=test%40seznam.cz&password=Peter&_=1562175129955”的资源由于 MIME 类型(“application/json”)不匹配(X-Content-Type-Options: nosniff)而被阻止。

获取access_token的jQuery函数

function authenticateUser(email, password) {
    var body = {
        grant_type: 'password',
        client_id: 'my-client',
        client_secret: 'my-secret',
        username: "test@seznam.cz",
        password: "Peter"
    };


    $.ajax({
        url: 'http://localhost:8080/oauth/token',
        crossDomain: true,
        type: 'POST',
        dataType: 'jsonp',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        header: {"Access-Control-Allow-Origin": "*"},
        data: body,
        complete: function(result) {
            alert(result);
        },

        success: function(result) {
            alert(result + " OK!");
        },

        error: function(result) {
            alert(result + " CHYBA");
        },
    });
    return true;
}

【问题讨论】:

    标签: javascript jquery ajax oauth-2.0 mime


    【解决方案1】:

    如果 javascript 文件由提供令牌的同一服务器提供服务,则无需在您的 jquery ajax 代码中使用完整的 url(也无需指明 crossDomain=true)。您的服务器似乎也期待 json 内容类型而不是 url 编码

    使用

            url: '/oauth/token',
            crossDomain: false,
    ...
            contentType: 'application/json; charset=UTF-8',
    

    提出请求


    编辑

    试试这个方法:

       $.post("/oauth/token",body,
      function(data, status) {
        alert("Data: " + data + "\nStatus: " + status);
      });
    

    希望对你有帮助

    【讨论】:

    • /oauth/token 写了 CORS 问题。当我使用整个网址时,它会返回:
    • {"error":"method_not_allowed","error_description":"请求方法 'GET' 不支持"}
    • 您最近是否更改过代码?该错误听起来就像您在期待另一个动词(如 POST 或 PUT)时对服务器执行 GET 请求。服务器是否执行另一个请求?
    • 我已经编辑了答案以包含 $.post jquery 方法示例。试试看
    • 我尝试了不需要 access_token 的端点并且它可以工作......但不幸的是,不是为了获得那些令牌:(我尝试了你的解决方案,但我再次遇到了 CORS 问题......:/
    猜你喜欢
    • 2015-03-31
    • 1970-01-01
    • 2015-12-19
    • 2012-06-07
    • 1970-01-01
    • 2011-03-26
    • 2017-08-29
    • 2015-07-15
    • 2021-04-10
    相关资源
    最近更新 更多