如何在 C# 中获取 OAuth 2.0 身份验证令牌 [英] How do I get an OAuth 2.0 authentication token in C#

查看:69
本文介绍了如何在 C# 中获取 OAuth 2.0 身份验证令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些设置:

  • Auth URL (which happens to be a "https://login.microsoftonline.com/...") if that helps.
  • Access Token URL "https://service.endpoint.com/api/oauth2/token"
  • ClientId "abc"
  • Clientsecret "123"

然后我需要使用标头中的不记名令牌进行 get 调用.

I then need to make a get call using a bearer token in the header.

我可以让它在 Postman 中工作,但是在试图找出如何在 C# 中实现它时遇到了困难.我一直在使用 RestSharp(但对其他人开放).这一切似乎都很不透明,当我认为它会很简单时:这是一个控制台应用程序,所以我不需要花里胡哨.

I can get this to work in Postman, but have hit a wall trying to work out how to implement it in C#. I've been using RestSharp (but open to others). It all seems so opaque, when I thought it'd be pretty straight forward: it's a console app, so I don't need bells and whistles.

最终,我希望我的应用程序(以编程方式)获取令牌,然后将其用于后续调用.我很感激任何人指点我的文档或示例,这清楚地解释了我所追求的内容.我遇到的一切都是部分的,或者是针对在不同流程上运行的服务.

Ultimately, I want my app to (programatically) get a token, then use that for my subsequent calls. I'd appreciate anyone pointing me to documentation or examples, that explains what I'm after clearly. Everything I've come across is partial or for services operating on a different flow.

谢谢.

推荐答案

在 Postman 中,单击 Generate Code 然后在 Generate Code Snippets 对话框中您可以选择不同的编码语言,包括 C# (RestSharp).

In Postman, click Generate Code and then in Generate Code Snippets dialog you can select a different coding language, including C# (RestSharp).

此外,您应该只需要访问令牌 URL.表单参数为:

Also, you should only need the access token URL. The form parameters are then:

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);

然后您可以从响应正文中获取您的访问令牌.例如,对于 Bearer 令牌类型,您可以将以下标头添加到后续经过身份验证的请求中:

From the response body you can then obtain your access token. For instance for a Bearer token type you can then add the following header to subsequent authenticated requests:

request.AddHeader("authorization", "Bearer <access_token>");

这篇关于如何在 C# 中获取 OAuth 2.0 身份验证令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆