By Daniel Du
In cloud service world, it is common for production cloud service to set some restrictions to avoid abuse usage, and it is common for cloud service metering the API calls as part of business model, for instance, charging by number of API calls. Although Autodesk do not have such business model yet, and it does not put API call restriction yet, it would be better to have such a mechanism to cache the access token and save the unnecessary API calls. If the access token is not expired, we do not need to access to authentication server to get a new one. I did a simple implementation in .net as below:
public class Util
{
private static readonly ILog logger = LogManager.GetLogger(typeof(Util));
string baseUrl = "";
RestClient m_client;
public static AccessToken token;
public static DateTime issueDateTime;
//refresh token if the token is about to expire in 5 seconds
public static int ABOUT_EXPIRED_SECONDS = 5;
public Util(string baseUrl)
{
this.baseUrl = baseUrl;
m_client = new RestClient(baseUrl);
}
public AccessToken GetAccessToken(string clientId, string clientSecret)
{
//no token or token is going to be expired
// (less than ABOUT_EXPIRED_SECONDS)
if (token == null
|| (DateTime.Now - issueDateTime).TotalSeconds
> (token.expires_in - ABOUT_EXPIRED_SECONDS))
{
RestRequest req = new RestRequest();
req.Resource = "authentication/v1/authenticate";
req.Method = Method.POST;
req.AddHeader("Content-Type", "application/x-www-form-urlencoded");
req.AddParameter("client_id", clientId);
req.AddParameter("client_secret", clientSecret);
req.AddParameter("grant_type", "client_credentials");
//avoid CORS issue, do not use this if you just need to get access token from same domain
req.AddHeader("Access-Control-Allow-Origin", "*");
IRestResponse<AccessToken> resp = m_client.Execute<AccessToken>(req);
logger.Debug(resp.Content);
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
AccessToken ar = resp.Data;
if (ar != null)
{
token = ar;
//update the token issue time
issueDateTime = DateTime.Now;
}
}
else
{
logger.Fatal("Authentication failed! clientId:" + clientId);
}
}
else
{
;//Do nothing, use the saved access token in static var
}
return token;
}
}
In this sample, I just cache the access token in memory with a static variable, you may use other more reliable storages such as database, memecached, etc.
Comments