尝试获取令牌时AngularJS 400错误的请求

时间:2019-01-30 09:36:57

标签: asp.net angularjs asp.net-web-api

我正在尝试从外部API获取令牌,当我尝试登录Web应用程序以及尝试通过邮递员发送请求时,此方法有效。对于此请求,我需要将内容类型设置为x-www-form-urlencoded。我知道如何执行此操作,但它似乎总是返回一个400错误的请求,并告诉我grant_type无效。因此,开始执行此任务的方法如下,将在登录时调用该代码:

代码如下:-

var _login = function (loginData) {
    var data = ["grant_type=password&username=", loginData.userName, "&password=", loginData.password].join('');

var deferred = $q.defer();
$http.post([serviceBase, "token"].join(''), data, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }).success(function (response) {
    console.log("login response", response);
    localStorageService.set(_keyAuthorizationData, { token: response.access_token, userName: loginData.userName });
    _authentication.isAuth = true;
    _authentication.userName = loginData.userName;
    deferred.resolve(response);
}).error(function (err, status) {
    _logOut();
    deferred.reject(err);
});
return deferred.promise;
};

loginData将由登录表单中的数据填充。

这是我对外部API的另一个调用,该API返回了400错误请求

var _transferPersoon = function (portal, data) {
    var externalAPI = "";
    if (portal == "portal1") {
        externalAPI = "https://urltoportal/webapi/";
    } else if (portal == "portal2") {
        externalAPI = "https://urltoportal/webapi/";
    } else if (portal == "portal3") {
        externalAPI = "https://urltoportal/webapi/";
    } else if (portal == "portal4") {
        externalAPI = "https://urltoportal/webapi/";
    } else {
        externalAPI = serviceBase;
    }

    var tokenData = {
        username: "cactustransfer",
        password: "bbbbbb",
        grant_type: "password"
    };
    var data = ["grant_type=password&username=", "transferaccount", "&password=", "password"].join('');

    $http.post([externalAPI, "token"].join(''), data, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }).success(function (response) {
        return response.access_token;
    })
}

这是返回并显示在Google chrome中的错误:

  

{错误:“ unsupported_grant_type”}

此请求正在通过我的ASP.NET Web API中的身份验证中间件发送和传递:

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        Cactus.Business.DataModel.GEBRUIKER gebruiker = null;
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);

        /*
         * Authenticatie methode voor het verplaatsen van personeel
         * Deze kan niet uitgevoerd worden als het request IP niet in het lijstje van hosts staat.
         * Dit is een extra beveiliging.
         */
        if (context.UserName == "cactustransfer")
        {
            if (!hostVerify.IsValidHost(context.Request.RemoteIpAddress))
            {
                using (UnitOfWork work = new UnitOfWork())
                {
                    gebruiker = work.GebruikerRepository.ValidateUser("transferaccount", "password");
                }
            }
        }

        if (gebruiker == null)
        {
            using (UnitOfWork work = new UnitOfWork())
            {
                gebruiker = work.GebruikerRepository.ValidateUser(context.UserName, context.Password);
                if (gebruiker == null)
                {
                    context.SetError("invalid_grant",
                        "The username or password is incorrect, or you have insufficient rights", context.Request.RemoteIpAddress);
                    return;
                }
            }
        }

        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));
        identity.AddClaim(new Claim("providerID", gebruiker.gebruikerId.ToString()));
        //identity.AddClaim(new Claim("providerID", gebruiker.persoon.ToString()));

        context.Validated(identity);
    }

这是我对邮递员及其结果进行测试的要求:

enter image description here

我已经检查并尝试了以下解决方案:

How do I POST urlencoded form data with $http without jQuery?

https://github.com/thephpleague/oauth2-server/issues/261

注意 我在Postman中使用的用户名实际上与transferaccount用户名相同

编辑:

这是Google chrome中显示的请求标头,第一个是登录名,它与本地API通信,第二个是尝试向外部API发送请求 enter image description here

enter image description here

更新:

有关使用外部API处理数据的所有功能已移至本地ASP.NET WEB API。这样,我知道如何使其工作。但这并不是真正的解决方案,而是一种解决方法。

1 个答案:

答案 0 :(得分:0)

尝试一下:

$http.post([externalAPI, "token", "?", data].join(''), {}, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }).success(function (response) {
      return response.access_token;
  })