首页 / .NET / 正文

.NET[C#] RestSharp中如何使用OAuth2认证?

7657 1 发布于: 2018-01-06 读完约需7分钟

.NET[C#] RestSharp中如何使用OAuth2认证?

问题描述

比如有使用RestSharp的如下模拟OAuth2的POST请求:

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

执行的结果服务端还是返回未授权,应该如何解决这个问题呢?

方案一

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

2.添加认证

client.Authenticator = new HttpBasicAuthenticator("client-app", "secret");

3.添加参数

request.AddParameter("client_id", "client-app");
request.AddParameter("client_secret", "secret");

4.设置 *Accept* header 为 `application/json`

方案二

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

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: .NET[C#]RestSharp中如何模拟发送POST请求?

下一篇: .NET[C#]Dapper中如何调用存储过程(Stored Procedure)的方法?

本文永久链接码友网 » .NET[C#] RestSharp中如何使用OAuth2认证?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册