Page History
...
A token can be generated with the POST /api/refresh-tokens end-point.
This service initializes a security token, and the access token is also returned in the request response. The access token needs to be provided in the header for all the other REST services mentioned in this document.
Token Generation Code
The following examples illustrate how to fetch an access token in various programming languages.
This Java Code example uses Apache HTTP Client and GSON for handling REST calls and JSON serialization. This also includes code for fetching an access token.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
package rest.code.examples;
import java.util.Random;
import org.apache.hc.client5.http.fluent.Content;
import org.apache.hc.client5.http.fluent.Request;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* Request an access token from the Yellowfin refresh-tokens REST end-point
*/
public class GetLoginToken {
public static void main(String[] args) throws Exception {
String host = "http://localhost:8080/yellowfinHead";
String restUsername = "admin@yellowfin.com.au";
String restPassword = "test";
Content c = Request.post(host + "/api/refresh-tokens")
.addHeader("Authorization", "YELLOWFIN ts=" + System.currentTimeMillis() + " , nonce=" + new Random().nextLong())
.addHeader("Accept", "application/vnd.yellowfin.api-v1+json")
.addHeader("Content-Type", "application/json")
.bodyString("{ \"userName\": \""+ restUsername + "\",\"password\": \""+ restPassword + "\"}", null)
.execute().returnContent();
JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
JsonElement accessToken = jsonObject.getAsJsonObject("_embedded").getAsJsonObject("accessToken").get("securityToken");
if (accessToken!=null) {
| ||||||
Section | ||||||
package rest.code.examples; import java.util.Random; import org.apache.hc.client5.http.fluent.Content; import org.apache.hc.client5.http.fluent.Request; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * Request an access token from the Yellowfin refresh-tokens REST end-point */ public class GetLoginToken { public static void main(String[] args) throws Exception { String host = "http://localhost:8080/yellowfinHead"; String restUsername = "admin@yellowfin.com.au"System.out.println("Access Token: " + accessToken); String} restPasswordelse = "test"; |
The following examples illustrate how to fetch an access token in various programming languages.
...
{
System.out.println("Token not retrieved");
}
}
} |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
namespace YellowfinAPIExamples; using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; class GetLoginToken package rest.code.examples; import java.util.Random; import org.apache.hc.client5.http.fluent.Content; import org.apache.hc.client5.http.fluent.Request; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * Request an access token from the Yellowfin refresh-tokens REST end-point */ public class GetLoginToken { publicstatic staticasync voidTask mainMain(Stringstring[] args) throws Exception { Stringstring host = "http://localhost:8080/yellowfinHead"; Stringstring restUsername = "admin@yellowfin.com.au"; string restPassword = "test"; using String(var restPasswordclient = "test"; new HttpClient()) Content{ c = Request.post(host + "/api/refresh-tokens") // Generate nonce .addHeader("Authorization", "YELLOWFIN ts=" + System.currentTimeMillis() + " ,long nonce =" + new Random().nextLongNextInt64()); .addHeader("Accept", "application/vnd.yellowfin.api-v1+json") // Create HTTP request var request = new .addHeader("Content-Type", "application/json")HttpRequestMessage(HttpMethod.Post, host + "/api/refresh-tokens"); .bodyString("{ \"userName\": \""+ restUsernamerequest.Headers.Add("Authorization", "YELLOWFIN ts=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "\",\"password\": \""+ restPassword + "\"}", null) nonce=" + nonce); .execute().returnContent(); request.Headers.Add("Accept", "application/vnd.yellowfin.api-v1+json"); JsonObject jsonObjectrequest.Content = new JsonParser().parse(c.asString()).getAsJsonObject();StringContent( JsonElement accessToken = jsonObject.getAsJsonObject("_embedded").getAsJsonObject("accessToken").get("securityToken"); if (accessToken!=null) { JsonConvert.SerializeObject(new { userName = restUsername, password = restPassword }), SystemMediaTypeHeaderValue.out.printlnParse("Access Token: " + accessToken); application/json") } else {); System.out.println("Token not retrieved"); // Send request and get response } } } | ||||||
Code Block | ||||||
| ||||||
namespace YellowfinAPIExamples; using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; class GetLoginToken { HttpResponseMessage response = await client.SendAsync(request); static async Task Main(string[] args) responseContent = await { response.Content.ReadAsStringAsync(); string host = "http://localhost:8080/yellowfinHead"; // Parse JSON response stringJObject restUsernamejsonObject = "admin@yellowfin.com.au"JsonConvert.DeserializeObject<JObject>(responseContent); string restPasswordaccessToken = "test"jsonObject["_embedded"]["accessToken"]["securityToken"].ToString(); using (var client = new HttpClient(if (!string.IsNullOrEmpty(accessToken)) { // Generate nonce Console.WriteLine("Access Token: " + accessToken); long nonce = new Random().NextInt64(); } else // Create HTTP request{ var request = new HttpRequestMessage(HttpMethod.Post, host + "/api/refresh-tokensConsole.WriteLine("Token not retrieved"); request.Headers.Add("Authorization", "YELLOWFIN ts=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + ", nonce=" + nonce); request.Headers.Add("Accept", "application/vnd.yellowfin.api-v1+json"); request.Content = new StringContent( } } } } |
Code Block | ||||
---|---|---|---|---|
| ||||
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "math/rand" "net/http" "time" ) func main() { host JsonConvert.SerializeObject(new { userName = restUsername, password = restPassword }), MediaTypeHeaderValue.Parse("application/json") := "http://localhost:8080/yellowfinHead" restUsername := "admin@yellowfin.com.au" restPassword := "test" // Generate nonce nonce := rand.Int63(); // Create request body // Send request and get response requestBody, err HttpResponseMessage response = await client.SendAsync(request); string responseContent = await response.Content.ReadAsStringAsync(); := json.Marshal(map[string]string{ "userName": restUsername, "password": restPassword, }) if err != // Parse JSON response nil { JObject jsonObject = JsonConvertfmt.DeserializeObject<JObject>(responseContent); Println("Error marshaling request body:", err) string accessToken = jsonObject["_embedded"]["accessToken"]["securityToken"].ToString(); return if (!string.IsNullOrEmpty(accessToken)) } { // Create HTTP client client := Console.WriteLine("Access Token: " + accessToken); &http.Client{} // Create HTTP request } request, err := http.NewRequest("POST", elsehost+"/api/refresh-tokens", bytes.NewBuffer(requestBody)) if err != nil { Consolefmt.WriteLinePrintln("TokenError notcreating retrievedrequest:", err); } } } } | ||||
Code Block | ||||
| ||||
package main import ( "bytes"return "encoding/json" } "fmt"// Add request headers "io/ioutil" "math/rand"request.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d", time.Now().UnixMilli(), nonce)) "net/http" "time" ) func main() {request.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json") host := "http://localhost:8080/yellowfinHead"request.Header.Set("Content-Type", "application/json") restUsername := "admin@yellowfin.com.au" // Send HTTP request response, restPassworderr := "test" client.Do(request) //if Generateerr nonce != nil { nonce := rand.Int63() // Createfmt.Println("Error sending request:", bodyerr) requestBody, err := json.Marshal(map[string]string{ return } "userName": restUsername, defer response.Body.Close() // Read response body "password": restPassword, responseBody, err }:= ioutil.ReadAll(response.Body) if err != nil { fmt.Println("Error marshalingreading requestresponse body:", err) return } // CreateParse HTTPJSON clientresponse clientvar := &http.Client{} // Create HTTP requestjsonResponse map[string]interface{} request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))err = json.Unmarshal(responseBody, &jsonResponse) if err != nil { fmt.Println("Error creatingparsing JSON requestresponse:", err) return } // Get Addaccess token requestfrom headersresponse request.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d", time.Now().UnixMilli(), nonce))accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string) request.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json") if !ok { request.Header.Set("Content-Type", "application/json") fmt.Println("Token not retrieved") // Send HTTP request return response, err := client.Do(request) } if err != nil { fmt.Println("Access Token:", accessToken) } |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
const fetch = require('node-fetch'); async function main() { const host = "http://localhost:8080/yellowfinHead"; const restUsername = "admin@yellowfin.com.au"; const restPassword = "test"; // Generate nonce const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); // Create request headers const headers = { 'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}`, 'Accept': 'application/vnd.yellowfin.api-v1+json', 'Content-Type': 'application/json' }; // Create request body const body = JSON.stringify({ userName: restUsername, password: restPassword }); try { // Make POST request const response = await fetch(`${host}/api/refresh-tokens`, { method: 'POST', headers: headers, body: body }); // Check if request was successful if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } // Parse JSON response const jsonResponse = await response.json(); const accessToken = jsonResponse._embedded.accessToken.securityToken; if (accessToken) { console.log(`Access Token: ${accessToken}`); } else { console.log("Token not retrieved"); } } catch (error) { console.error("Error:", error.message); } } main(); |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<?php function main() { $host = "http://localhost:8080/Yellowfin"; $restUsername = "admin@yellowfin.com.au"; $restPassword = "test"; // Generate nonce $nonce = mt_rand(); // Create request body $requestBody = json_encode(array( "userName" => $restUsername, "password" => $restPassword )); // Create request headers $headers = array( 'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce, 'Accept: application/vnd.yellowfin.api-v1+json', 'Content-Type: application/json' ); $response = httpRequest('POST', "$host/api/refresh-tokens", $headers, $requestBody); // Parse JSON response $jsonResponse = json_decode($response, true); // Get access token from response if (isset($jsonResponse["_embedded"]["accessToken"]["securityToken"])) { $accessToken = $jsonResponse["_embedded"]["accessToken"]["securityToken"]; echo "Access Token: " . $accessToken; } else { echo "Token not retrieved"; } } function httpRequest($method, $url, $headers, $data = null) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); if ($data !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } $response = curl_exec($ch); if (curl_errno($ch)) { throw new Exception('Error: ' . curl_error($ch)); } curl_close($ch); return $response; } main() ?> |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
import json import random import time import requests host = "http://localhost:8080/yellowfinHead" rest_username = "admin@yellowfin.com.au" rest_password = "test" # Generate nonce nonce = random.randint(0, 2**63 - 1) # Create request body request_body = json.dumps({ "userName": rest_username, "password": rest_password }) # Create request headers headers = { 'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}', 'Accept': 'application/vnd.yellowfin.api-v1+json', 'Content-Type': 'application/json' } # Send HTTP request response = requests.post(host + "/api/refresh-tokens", headers=headers, data=request_body) # Check response status if response.status_code == 200: # Parse JSON response json_response = response.json() access_token = json_response["_embedded"]["accessToken"]["securityToken"] print("Access Token:", access_token) else: print("Token not retrieved") |
...