使用Web API从JQuery请求令牌

时间:2015-07-09 14:56:35

标签: jquery authentication asp.net-web-api2 jwt

我在Javascript中执行ajax-request以从我的WebAPI AuthenticationProvider获取JWT。这是我的js-function:

    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":"密码"" CLIENT_ID":" myClientId"" client_secret":& #34; myClientSecret""用户名":"演示""密码":" 123"}

1 个答案:

答案 0 :(得分:2)

看起来你可能已经解决了它,但这就是为我做的事情。使用上面的设置和设置这个工作。

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