我有这些设置:
- Auth URL(恰好是一个 "https://login.microsoftonline.com/ ...") 如果有帮助的话。
- 访问 token 网址“https://service.endpoint.com/api/oauth2/token”
- 客户ID "abc"
- 客户端密码“123”
然后我需要使用 header 中的不记名 token 进行 get 调用。
我可以让它在 Postman 中运行,但在尝试找出如何在 C# 中实现它时遇到了困难。我一直在使用 RestSharp(但对其他人开放)。当我认为它会非常简单时,这一切看起来是如此不透明:它是一个控制台应用程序,所以我不需要花里胡哨的东西。
最终,我希望我的应用程序(以编程方式)获取 token ,然后将其用于我的后续调用。我很感激任何人向我指出文档或示例,这些文档或示例清楚地解释了我所追求的内容。我遇到的一切都是部分的或针对在不同流程上运行的服务。
谢谢。
最佳答案
在 Postman 中,单击生成代码,然后在生成代码片段对话框中,您可以选择不同的编码语言,包括 C# (RestSharp)。
此外,您应该只需要访问 token URL。表单参数是:
grant_type=client_credentials
client_id=abc
client_secret=123
代码片段:
/* using RestSharp; // https://www.nuget.org/packages/RestSharp/ */
var client = new RestClient("https://service.endpoint.com/api/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=abc&client_secret=123", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
然后您可以从响应正文中获取您的访问 token 。例如,对于 Bearer token 类型,您可以将以下 header 添加到后续经过身份验证的请求中:
request.AddHeader("authorization", "Bearer <access_token>");
关于c# - 如何在 C# 中获取 OAuth 2.0 身份验证 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38494279/