首页 > 解决方案 > 使用 Ajax 调用 ValidateClientAuthentication 时,ClientId 为 null

问题描述

我有以下由 POSTMAN 生成的代码:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:51734/token",
  "method": "POST",
  "headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    "Accept": "application/json",
    "cache-control": "no-cache",
    "Postman-Token": "2879f786-3b1f-42fe-8198-b2193764d165"
  },
  "data": {
    "grant_type": "client_credentials",
    "client_id": "6E1JIQDEF0M"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

当您运行上面的代码时,首先执行以下代码:

        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {

            string clientId = string.Empty;
            string clientSecret = string.Empty;
            ClientDTO client = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                //Remove the comments from the below line context.SetError, and invalidate context 
                //if you want to force sending clientId/secrects once obtain access tokens. 
                context.Validated();
                //context.SetError("invalid_clientId", "ClientId should be sent.");
                //return Task.FromResult<object>(null);
                return;
            }
}

我遇到的问题是 context.ClientId 始终为空,我不知道为什么。

当我使用 C# 发出相同的请求时,它可以工作:

        var client = new RestClient("http://localhost:51734/token");
        var request = new RestRequest(Method.POST);
        request.AddHeader("Postman-Token", "db182d32-9eff-4150-815e-2fd7d10ebd58");
        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("Accept", "application/json");
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        request.AddParameter("undefined", "grant_type=client_credentials&client_id=6E1JIQDEF0M&undefined=", ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);

那么为什么它适用于 c# 而不是 javascript?任何有任何想法的人?

标签: javascriptc#ajaxasp.net-mvc

解决方案


尝试从 Javascript 中这样调用。

data : 'grant_type=client_credentials&client_id=6E1JIQDEF0M'


推荐阅读