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

查看:780
本文介绍了如何在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.

我可以在邮递员中使用它,但是碰壁了找出如何在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中,单击生成代码,然后在生成代码片段对话框中,选择其他编码语言,包括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天全站免登陆