【问题标题】:unsupported_grant_type in Web Api 2Web Api 2 中的 unsupported_grant_type
【发布时间】:2016-12-04 00:52:11
【问题描述】:

我是 Web Api 的初学者,正在实施授权和身份验证,但遇到了一些错误,如下所述:

从 webApi 获取令牌时出现此错误

{"readyState":4,"responseText":"{\"error\":\"unsupported_grant_type\"}","responseJSON":{"error":"unsupported_grant_type"},"status":400,"statusText":"Bad Request"}

这是我请求令牌的 jQuery 代码

$(document).ready(function () {
    $("#login").click(function () {
        debugger;
        var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
        console.log(details);
        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            data: details,
            url: "http://localhost:59926/token",
            success: function (data) { console.log(JSON.stringify(data)); },
            error: function (data) { console.log(JSON.stringify(data)); }
        });
    });

【问题讨论】:

  • contentType 应该是application/json

标签: ajax authentication asp.net-web-api authorization asp.net-web-api2


【解决方案1】:

您的data 应该是查询字符串,而不是 JSON 对象。如果需要,您应该对参数进行编码

data: 'username=' + encodeURIComponent(user.username) + '&password=' + encodeURIComponent(user.password) + '&grant_type=password'

【讨论】:

    【解决方案2】:

    contentType 是错误的。应该是application/json

    $(document).ready(function () {
        $("#login").click(function () {
            debugger;
            var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
            console.log(details);
            $.ajax({
                type: "POST",
                contentType: "application/json",
                data: details,
                url: "http://localhost:59926/token",
                success: function (data) { console.log(JSON.stringify(data)); },
                error: function (data) { console.log(JSON.stringify(data)); }
            });
        });
    

    【讨论】:

    • 但我遇到了同样的错误:{"readyState":4,"responseText":"{\"error\":\"unsupported_grant_type\"}","responseJSON":{"error":"unsupported_grant_type"},"status":400,"statusText":"Bad Request"}
    • 同时发布您的 webapi 代码以及您尝试实现身份验证的方式
    猜你喜欢
    • 2016-06-22
    • 2019-04-22
    • 2021-10-02
    • 1970-01-01
    • 2018-04-25
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    相关资源
    最近更新 更多