GET Token - C#

The Token service is a compulsory RESTful API for integrated users to retrieve a token which will be submitted as part of the request header for authentication purposes on every API request call. A valid token must be provided within each API call. Tokens are only valid for 20 minutes. The Token API will be added by default to all APPs created.

REVEAL integration users are provided with a REST username and password. The integration credentials will not be the same as the user’s email address and password used to access the integration manager portal. Every REST integration credential is associated with one REVEAL account.

To retrieve a successful token, the integration username and password needs to be converted to BASE64, as shown in the sample below.

Main Method

using System; // Note: This can be omitted if Console.WriteLine is not used

namespace Rest_Token_Example
{
class Program
{
static void Main()
{
// Set local variables
string username = "username";
string password = "password";
string getTokenURI = "https://fim.api.ENV.fleetmatics.com/token";

// Pass variables to create a new TokenGenerator object
var token = new TokenGenerator(username, password, getTokenURI);

// Display token string
Console.WriteLine(token.AuthString);
}
}
}

Token Generator Class

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace Rest_Token_Example
{
public class TokenGenerator
{
private string _authString { get; set; }

private int _retryCount { get; set; }

private DateTime _expiredDateTimeUtc { get; set; }

private string _username { get; set; }

private string _password { get; set; }

private string _getTokenUri { get; set; }

// Public property that returns the token string. The logic contained
// evaluates if the token is expired when it is accessed. If expired,
// a new token is automatically populated, and new token string returned
public string AuthString
{
get
{
if (_expiredDateTimeUtc < DateTime.UtcNow)
{
_authString = GetToken();
}
return _authString;
}
}

// Constructor that takes username, password, and enpoint for the Token API
public TokenGenerator(string username, string password, string uri)
{
// Set private properties
_getTokenUri = uri;
_username = username();
_password = password();
_authString = GetToken();
}
private string GetToken()
{
string error;
do
{
// Build authentication and store in variable
string authenticationString = BuildBasicAuthenticationString(_username, _password);

// Begin new HttpClient. Use "using" to ensure the resource is released
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain")); // Set expected result type
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authenticationString); // Pass in stored authentication string to "Basic" Auth header

// Begin getting the response from the REST API call, passing in the endpoint to the method
using (HttpResponseMessage response = client.GetAsync(_getTokenURI).Result)
{
// True if HttpStatusCode was in the Successful range (200-299); otherwise false
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Token successfully retrieved"); // Logging
_expiredDateTimeUtc = DateTime.UtcNow.AddMinutes(20); // Set expiry field to current time and add 20 minutes (tokens are no longer valid after 20 mins)
_retryCount = 0; // Reset retry counter
return response.Content.ReadAsStringAsync().Result; // Return authentication string
}

// Only if call has failed (Not 200) will this block be reached.
// Increment retry counter and log error.
_retryCount++;
error = string.Format("{0}, {1}", (int)response.StatusCode, response.ReasonPhrase);
Console.WriteLine("Http Error {0}. Problem getting token", error);
}
}
} while (_retryCount < 3); // If call fails, retry 3 times before throwing Exception

// Call has faild 3 consecutive times, reset retry counter and throw Exception
_retryCount = 0;
throw new Exception(string.Format("Failed 3 retries! Error {0}", error));
}

// Converts supplied username and password to byte array which is then converted to
// a Base64 encoded string and returned
private static string BuildBasicAuthenticationString(string username, string password)
{
var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password));
return Convert.ToBase64String(byteArray);
}
}
}

Downloadable source code for this example is available as a Microsoft Visual Studio solution in a .zip file.
To download source code for this example, click HERE.

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.