简体   繁体   English

如何使用jQuery(localhost)获得oauth access_token?

[英]How to get oauth access_token with jQuery (localhost)?

I am trying to get access_token utilizing jQuery. 我正在尝试使用jQuery获取access_token。 Problem is, that I cannot get that token (server is running on localhost). 问题是,我无法获得该令牌(服务器正在本地主机上运行)。 Server works fine (I tried that with postman), but I cannot get it with jQuery. 服务器工作正常(我曾用邮递员尝试过),但我无法使用jQuery来获得它。 Browser writes after clicking on the button. 单击该按钮后,浏览器写入。

The resource from “ 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 ” was blocked due to MIME type (“application/json”) mismatch (X-Content-Type-Options: nosniff). 从资源“ 的http://本地主机:8080 /的OAuth /令牌回调= jQuery34105901959820360243_1562175129954&grant_type =密码&CLIENT_ID =我的客户端和client_secret =我的秘密和用户名=测试%40seznam.cz和密码=彼得&_ = 1562175129955 ”被阻断,由于MIME类型(“应用程序/ json”)不匹配(X-Content-Type-Options:nosniff)。

jQuery function to get access_token jQuery函数获取access_token

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;
}

If the javascript file is served by the same server that gives out the tokens then there's no need to use the full url in your jquery ajax code (and there's no need to indicate crossDomain=true). 如果javascript文件由发出令牌的同一台服务器提供服务,则无需在jquery ajax代码中使用完整的url(也无需指示crossDomain = true)。 It also seems that your server is expecting json content type instead of url-encoded 似乎您的服务器正在使用json内容类型,而不是url编码

use 采用

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

To make the request 提出要求


Edit 编辑

Trye this way: 尝试这种方式:

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

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM