Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to refresh access token using refresh token?

$
0
0

I can't find a tutorial or a code example where it shows how/when to refresh the access token. How to implement refreshing the new access token when it is about to expire?

This is what I have so far:

This is the class where to get the new access token and refresh token.

namespace DemoApp
{
    public class Tokens
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public int expires_in { get; set; }
        public string refresh_token { get; set; }
    }

    public class AccessToken 
    {
        public void GetNewAccessToken()
        {
            Tokens localTokens = new Tokens();

            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.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&refresh_token=" + localTokens.refresh_token, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            var responseContent = response.Content;

            var newTokensList = new JavaScriptSerializer().Deserialize<Tokens>(responseContent);

            localTokens.access_token = newTokensList .access_token;
            localTokens.refresh_token = newTokensList .refresh_token;
        }
    }
}

This is the class where it call the API, with the new Access Token, to get the new data.

namespace DemoApp
{
    public class API
    {
        public Data()
        {
            public void CallAPI()
            {
                Tokens tokens = new Tokens();
                var client = new RestClient("www.example.com/api");
                var request = new RestRequest(Method.GET);
                request.AddHeader("authorization", "Bearer " + tokens.access_token);
                request.AddHeader("accept", "application/json; charset=utf-8");
                IRestResponse response = client.Execute(request);

                var data = response.Content;
            }
        }
    }
}

Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>