首页 > 解决方案 > 如何向kong插件请求OAuth2令牌

问题描述

我正在关注本教程https://medium.com/@far3ns/kong-oauth-2-0-plugin-38faf938a468并且当我请求令牌时

Headers: Content-Type:application/json
Host:api.ct.id
Body:
{
“client_id”: “CLIENT_ID_11”,
“client_secret”: “CLIENT_SECRET_11”,
“grant_type”: “password”,
“provision_key”: “kl3bUfe32WBcppmYFr1aZtXxzrBTL18l”,
“authenticated_userid”: “oneone@gmail.com”,
“scope”: “read”
} 

它返回

{
  "error_description": "Invalid client authentication",
  "error": "invalid_client"
}

无论我尝试了什么,我都无法修复它,知道如何让它正常工作

标签: python-3.xhttphttpsoauth-2.0kong

解决方案


这是有效的 c# 代码。

选项1

public static string GetOAuthToken(string url, string clientId, string clientSecret, string scope = "all", string grantType = "client_credentials")
        {
            try
            {
                string token = "";
                if (string.IsNullOrWhiteSpace(url)) throw new ArgumentException("message", nameof(url));
                if (string.IsNullOrWhiteSpace(clientId)) throw new ArgumentNullException("message", nameof(clientId));
                if (string.IsNullOrWhiteSpace(clientSecret)) throw new ArgumentNullException("message", nameof(clientSecret));

                var oAuthClient = new RestClient(new Uri(url));
                var request = new RestRequest("Authenticate", Method.POST);

                request.AddHeader("Content-Type", "application/json");

                var credentials = new
                {
                    grant_type = grantType,
                    scope = scope,
                    client_id = clientId,
                    client_secret = clientSecret
                };

                request.AddJsonBody(credentials);

                var response = oAuthClient?.Execute(request);
                var content = response?.Content;

                if (string.IsNullOrWhiteSpace(content)) throw new ArgumentNullException("message", nameof(clientSecret));
                token = content?.Trim('"');

                return token;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message,ex);
            }
        }

选项 2

var httpClient = new HttpClient()
var creds = $"client_id={client_id}&client_secret{client_secret}&grant_type=client_credentials";
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var content = new StringContent(creds, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = httpClient.PostAsync("https://myorg/oauth/oauth2/cached/token", content).Result;
var OAuthBearerToken = response.Content.ReadAsStringAsync().Result;

推荐阅读