Wednesday, March 17, 2021

How to implement request and response oAuth2 with RestSharp?



I am calling an API with access token that expire in 1799 seconds (approximately 30 minutes). What is the right to handle this? or how to use the refresh token to get a new access token, once the access token expires, without having to submit credentials again.

This is what I have so far:

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

} 

No comments:

Post a Comment