Skip to main content
 首页 » 编程设计

jquery之从 Web API 使用 JQuery 请求 token

2026年05月17日63JustinYoung

我正在 Javascript 中执行 ajax 请求,以从我的 WebAPI AuthenticationProvider 获取 JWT。这是我的 js 函数:

    function authenticateUser(credentials) { 
    var body = { 
        grant_type: 'password', 
        client_id: 'myClientId', 
        client_secret: 'myClientSecret', 
        username: credentials.name, 
        password: credentials.password 
    }; 
 
    $.ajax({ 
        url: 'http://localhost:9000/token', 
        type: 'POST', 
        dataType: 'json', 
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
        /* data: JSON.stringify(body), /* wrong */ 
        data: body, /* right */ 
        complete: function(result) { 
            //called when complete 
            alert(result); 
        }, 
 
        success: function(result) { 
            //called when successful 
            alert(result); 
        }, 
 
        error: function(result) { 
            //called when there is an error 
            alert(result); 
        }, 
    }); 
    session.isAuthenticated(true); 
    return true; 
} 

尽管在我看来内容发送方式正确,但 OAuthValidateClientAuthenticationContext 只有空值。

从控制台复制的我的表单数据:

{"grant_type":"password","client_id":"myClientId","client_secret":"myClientSecret","username":"demo","password":"123"}

请您参考如下方法:

看起来你可能已经解决了这个问题,但是,这就是为我做的。使用上面的内容并将主体设置为此有效。

var body = { 
    grant_type: 'password', 
    username: credentials.name, 
    password: credentials.password 
};