如何在C#中使用RestSharp实现oAuth2?

时间:2019-12-05 18:11:22

标签: c# api oauth-2.0 restsharp

我正在调用带有访问令牌的API,该令牌将在1799秒(约30分钟)内到期。处理此事的权利是什么?或访问令牌过期后如何使用刷新令牌获取新的访问令牌,而无需再次提交凭据。

这是我到目前为止所拥有的:

public void api()
{
    string token = "";

    try {
        callApi(token);
    }
    catch(Exception)
    {
        var client = new RestClient("www.example.com/api/token");
        var request = new RestRequest(Method.POST);
        request.AddHeader("content-type", "application/x-www-form-urlencoded");
        request.AddHeader("cache-control", "no-cache");
        request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=us&password=pas", ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);

        dynamic resp = JObject.Parse(response.Content);
        token = resp.access_token;

        callApi(token);
    }
}

public void callApi(string token)
{
    var client = new RestClient("www.example.com/api/data");
    var request = new RestRequest(Method.GET);
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("authorization", "Bearer " + token);
    request.AddHeader("accept", "application/json; charset=utf-8");
    IRestResponse response = client.Execute(request);
}

0 个答案:

没有答案