如何在RestSharp中使用OAuth2

Dim*_*ris 27 c# rest curl restsharp oauth-2.0

在服务器端(Spring java)整理出OAuth2几天之后,我开始研究用C#编写的客户端.我正在使用RestSharp来调用我的Web API,但我对OAuth2有很大的困难.几乎没有任何文档,我在网上找到的几个例子都不起作用.有人能为我提供一个最新的代码示例,我可以使用吗?

到目前为止,我有以下内容:

var client = new RestClient("http://example.com/myapi/oauth/token");
RestRequest request = new RestRequest() { Method = Method.POST };

request.AddHeader("Content-Type", "application/json");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", "client-app");
request.AddParameter("client_secret", "secret");

var response = client.Execute(request);
Run Code Online (Sandbox Code Playgroud)

我只是在调试模式下运行此代码,当我查看响应时,我未经授权.

当我使用相同的参数在控制台上卷曲时它工作正常,但似乎我不能使它在C#中工作.这是curl命令:

curl -H "Accept: application/json" client-app:secret@example.com/myapi/oauth/token -d grant_type=client_credentials
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我用占位符替换了我的真实API网址和其他信息.

Pau*_*tha 50

请参阅RFC 6749 - 4.4.2.客户端凭据 - 访问令牌请求

这是请求的基本格式

POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
Run Code Online (Sandbox Code Playgroud)

您的cURL请求

curl -H "Accept: application/json" \
     -d grant_type=client_credentials \
     client-app:secret@example.com/myapi/oauth/token 
Run Code Online (Sandbox Code Playgroud)

您的cURL命令工作的原因

  1. Content-TypePOST时默认(如果未指定)(使用-d开关时默认)是application/x-www-form-urlencoded
  2. 默认身份验证类型(如果未指定)是Basic.用户名和密码通过-u选项或URL 传递

    -u username:password (client-app:secret)
    
    -- or put it in the url --
    
    client-app:secret@example.com/myapi/oauth/token
    
    Run Code Online (Sandbox Code Playgroud)

    您还可以使用--basic或指定身份验证类型--digest

您可以使用-vcURL命令中的开关查看请求中涉及的所有标头.

RestSharp修复:

  1. 设置Content-Typeapplication/x-www-form-urlencoded

  2. 添加基本​​身份验证

    client.Authenticator = new HttpBasicAuthenticator("client-app", "secret");
    
    Run Code Online (Sandbox Code Playgroud)
  3. 摆脱

    request.AddParameter("client_id", "client-app");
    request.AddParameter("client_secret", "secret");
    
    Run Code Online (Sandbox Code Playgroud)
  4. Accept标题设置为application/json

  • 谢谢,难怪你有47K积分.这就像一场梦.现在我需要弄清楚如何在需要时刷新访问令牌. (2认同)