简体   繁体   English

如何在RestSharp中使用OAuth2

[英]How to use OAuth2 in RestSharp

After a couple of days sorting out OAuth2 at the server-end (Spring java) I started working on the client written in C#. 在服务器端(Spring java)整理出OAuth2几天之后,我开始研究用C#编写的客户端。 I am using RestSharp to call my web API but I am having real difficulty with the OAuth2. 我正在使用RestSharp来调用我的Web API,但我对OAuth2有很大的困难。 There is hardly any documentation and the few examples I found online do not work. 几乎没有任何文档,我在网上找到的几个例子都不起作用。 Can someone provide me a code sample that is up to date and that I can use? 有人能为我提供一个最新的代码示例,我可以使用吗?

So far I have the following: 到目前为止,我有以下内容:

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

I am simply running this code in debug mode and when I look into the response I get unauthorized. 我只是在调试模式下运行此代码,当我查看响应时,我未经授权。

When I do curl on the console with the same parameters it works fine but it seems I can't make this to work in C#. 当我使用相同的参数在控制台上卷曲时它工作正常,但似乎我不能使它在C#中工作。 Here is the curl command: 这是curl命令:

curl -H "Accept: application/json" client-app:secret@example.com/myapi/oauth/token -d grant_type=client_credentials

By the way, I have replaced my true API urls and other information with placeholders. 顺便说一句,我用占位符替换了我的真实API网址和其他信息。

See RFC 6749 - 4.4.2. 请参阅RFC 6749 - 4.4.2。 Client Credentials - Access Token Request 客户端凭据 - 访问令牌请求

Here is the basic format of the request 这是请求的基本格式

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

grant_type=client_credentials

Your cURL request 您的cURL请求

curl -H "Accept: application/json" \
     -d grant_type=client_credentials \
     client-app:secret@example.com/myapi/oauth/token 

The reason your cURL command works 您的cURL命令工作的原因

  1. Default Content-Type (if not specified) with POST (default when you use -d switch) is application/x-www-form-urlencoded 使用POST的默认Content-Type (如果未指定)(使用-d开关时为默认值)是application/x-www-form-urlencoded
  2. Default authentication type, if not specified, is Basic . 默认身份验证类型(如果未指定)是Basic The username and password are passed either through the -u option or in the URL 用户名和密码通过-u选项或URL传递

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

    You could also specify the auth type with --basic or --digest 您还可以使用--basic--digest指定身份验证类型

You can use the -v switch in your cURL command to see all the headers involved in the request. 您可以在cURL命令中使用-v开关来查看请求中涉及的所有标头。

RestSharp fix: RestSharp修复:

  1. Set the Content-Type to application/x-www-form-urlencoded Content-Type设置为application/x-www-form-urlencoded

  2. Add the Basic authentication 添加基本​​身份验证

     client.Authenticator = new HttpBasicAuthenticator("client-app", "secret"); 
  3. Get rid of 摆脱

     request.AddParameter("client_id", "client-app"); request.AddParameter("client_secret", "secret"); 
  4. Set the Accept header to application/json Accept标头设置为application/json

I am able to get both of the following functions worked. 我能够完成以下两个功能。

 public RestClient getClient2(string user, string token)
    {
        RestClient client = new RestClient();
        client.BaseUrl = new Uri(baseUrl);
        client.Authenticator = new HttpBasicAuthenticator(user, token);                
        //client.Authenticator = new OAuth2UriQueryParameterAuthenticator(token); //works
        //client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(token); // doesn't work

        return client;
    }

  public GitHubUser GetGitHubUser2()
    {
        RestRequest request = new RestRequest();        
        request.Resource = "/users/huj";
        request.RootElement = "GitHubUser";

        RestClient client = getClient2(myUser, myToken);

        return Execute<GitHubUser>(client, request);        
    }


    /// <summary>
    /// http://stackoverflow.com/questions/30133937/how-to-use-oauth2-in-restsharp
    /// </summary>
    /// <returns>GitHubUser</returns>
    public GitHubUser GetGitHubUser3()
    {
        //RestRequest request = new RestRequest(Method.POST);  //empty data
        RestRequest request = new RestRequest();
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        request.AddHeader("Accept", "application/json");
        request.AddParameter("grant_type", "client_credentials");

        request.Resource = "/users/huj";
        request.RootElement = "GitHubUser";

        RestClient client = getClient2(myUser, myToken);

        return Execute<GitHubUser>(client, request);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM