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.
<?php $username = 'USERNAME'; $password = 'PASSWORD'; $FIM_endpoint = 'https://fim.api.ENV.fleetmatics.com/token'; //Call method and set variable to authorization string $token = get_token($FIM_endpoint, $username, $password); echo $token; function get_token($url, $username, $password) { //Create necessary headers for REST call $headers = array(); $headers[] = make_authorization_header($username, $password); //Send to function to Base64 encode $headers[] = 'Accept: text/plain'; //Authorization token comes back as plain text $session = curl_init($url); //Initialize transfer with URL curl_setopt($session, CURLOPT_HEADER, false); //Exclude header info in response curl_setopt($session, CURLOPT_RETURNTRANSFER, true); //Return transfer as a string of the return value of curl_exec() curl_setopt($session, CURLOPT_HTTPHEADER, $headers); //Pass in headers //Execute transfer of $session $response = curl_exec($session); //Get http code outcome of the #session transfer $http_code = curl_getinfo($session, CURLINFO_HTTP_CODE); //Measure false response/error if($response === false) { echo 'Error: '. curl_error($session); } //ALWAYS close transfer connection curl_close($session); //Evaluate variable for non 200(OK) http code if($http_code !== 200) { echo 'Error: Http Status Code returned '.$http_code; } return $response; } function make_authorization_header($username, $password) { //Base64 encode username:password; note: the ':' must be present between them $encodedString = base64_encode($username.':'.$password); //Return concatenated Authorization string return 'Authorization: Basic '.$encodedString; } ?>
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.
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.
public class Program{ public static void main(String[] args){ // 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 TokenGenerator token = new TokenGenerator(username, password, getTokenUri); // Display auth string System.out.println(token.GetAuthString()); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.net.ssl.HttpsURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Base64; import java.util.Date; import java.util.Calendar; public class TokenGenerator{ private String _authString; private Date _expiredDateTime; private String _username; private String _password; private String _getTokenUri; // 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 GetAuthString(){ Date now = new Date(); if(now.after(_expiredDateTime)){ this._authString = GetToken(); } return this._authString; } // Constructor that takes username, password, and enpoint for the Token API public TokenGenerator(String username, String password, String getTokenUri){ _username = username; _password = password; _getTokenUri = getTokenUri; _authString = GetToken(); } private String GetToken(){ String authString = ""; try { // Get authentication, Base64 encoded, string String basicAuth = BuildBasicAuth(_username, _password); URL url = new URL(_getTokenUri); // Construct a url with the earlier supplied GetToken URI HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // Open a new Https connection for transmission conn.setRequestMethod("GET"); // Set request type to GET conn.setRequestProperty("Authorization", basicAuth); // Pass in auth string into Authorization header conn.setRequestProperty("Accept", "text/plain"); // Denote type of response expected conn.setDoOutput(false); // Do not send request body // Execute request, read response. If we do not receive a 200 OK, throw exception if (conn.getResponseCode() != HttpsURLConnection.HTTP_OK) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } // Reads text from a character-input stream BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); this.SetExpiredDateTime(); // Set expiration date of token (expires after 20 minutes) authString = br.readLine(); // Read the buffer into the authString variable, not including any line-termination characters conn.disconnect(); // Close HttpsURLConnection } catch (MalformedURLException e) { // Required Exception e.printStackTrace(); } catch (IOException e) { // Required Exception e.printStackTrace(); } return authString; } // Supply username and password to build a Base64 encoded authentication string private static String BuildBasicAuth(String username, String password) { String userCredentials = username + ":" + password; // Prepare user credentials for encoding return "Basic " + Base64.getEncoder().encodeToString(userCredentials.getBytes()); // Base64 encode the user credentials and append to "Basic " and return } // Set the newly acquired token's expiration date and time private void SetExpiredDateTime(){ Calendar now = Calendar.getInstance(); // Get current date time now.add(Calendar.MINUTE, 20); // Add twenty minutes (token is invalid after this time frame) this._expiredDateTime = now.getTime(); // set expired date time to a date representing the time value plus twenty minutes. } }
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.
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.
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); } } }
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(); // Set expected result type client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain")); // Pass in stored authentication string to "Basic" Auth header client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authenticationString); // 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) { // Logging Console.WriteLine("Token successfully retrieved"); // Set expiry field to current time and add 20 minutes (tokens are no longer valid after 20 mins) _expiredDateTimeUtc = DateTime.UtcNow.AddMinutes(20); // Reset retry counter _retryCount = 0; // Return authentication string return response.Content.ReadAsStringAsync().Result; } // 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); } } }
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.
To open and use the zipped Visual Studio projects, you will need a copy of Microsoft Visual Studio. Unzip the file and click on the Visual Studio solution file to begin, after the above requirements have been met.
Xamarin Workbooks provide a blend of documentation and code that is perfect for experimentation, learning, and creating code. To be able to view the interactive workbooks provided by Fleetmatics, please check the specific requirements for your OS and install Xamarin Workbooks, here.