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

.NET 作者: Rector 707阅读 0评论 0收藏 收藏本文

郑重申明:本文未经许可,禁止任何形式转载

.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中如何使用OAuth2认证?

发布于: 2018-01-06 09:11:17
分享扩散:

文章评论

获取验证码