python-3.x - 如何向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"
}
无论我尝试了什么,我都无法修复它,知道如何让它正常工作
解决方案
这是有效的 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;
推荐阅读
- json - json.load() 从文件到字典返回错误
- ios - 存储动态字符串
- ios - 如何将图像从框架发送到 iOS Swift 中的示例项目?
- reactjs - 为什么我的变量在第一次单击 Apollo Client React 时为空?
- mule - 如何将依赖项添加到 Mulesoft 设计中心 (IPaSS)
- python - 通过请求将数据发布到 Google Analytics
- ios - 使用协议对类似 UITableViewCell 进行分组以减少代码
- php - 如何使用 php 和 socket.io 连接前端?
- django - Django 应用程序中何时生成 Django 会话密钥?
- android - Proguard (R8) 否定操作员不工作以保留某些包以外的任何东西