Page History
...
The following examples illustrate how to fetch an access token in various programming languages.
Java
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) {
System.out.println("Access Token: " + accessToken);
} else {
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 { static async Task Main(string[] args) { string host = "http://localhost:8080/yellowfinHead"; string restUsername = "admin@yellowfin.com.au"; string restPassword = "test"; using (var client = new HttpClient()) { // Generate nonce long nonce = new Random().NextInt64(); // Create HTTP request var request = new HttpRequestMessage(HttpMethod.Post, host + "/api/refresh-tokens"); 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( JsonConvert.SerializeObject(new { userName = restUsername, password = restPassword }), MediaTypeHeaderValue.Parse("application/json") ); // Send request and get response HttpResponseMessage response = await client.SendAsync(request); string responseContent = await response.Content.ReadAsStringAsync(); // Parse JSON response JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent); string accessToken = jsonObject["_embedded"]["accessToken"]["securityToken"].ToString(); if (!string.IsNullOrEmpty(accessToken)) { Console.WriteLine("Access Token: " + accessToken); } else { Console.WriteLine("Token not retrieved"); } } } } |
Code Block | ||||
---|---|---|---|---|
| ||||
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "math/rand" "net/http" "time" ) func main() { host := "http://localhost:8080/yellowfinHead" restUsername := "admin@yellowfin.com.au" restPassword := "test" // Generate nonce nonce := rand.Int63() // Create request body requestBody, err := json.Marshal(map[string]string{ "userName": restUsername, "password": restPassword, }) if err != nil { fmt.Println("Error marshaling request body:", err) return } // Create HTTP client client := &http.Client{} // Create HTTP request request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody)) if err != nil { fmt.Println("Error creating request:", err) return } // Add request headers request.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d", time.Now().UnixMilli(), nonce)) request.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json") request.Header.Set("Content-Type", "application/json") // Send HTTP request response, err := client.Do(request) if err != nil { |
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)); |
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") |