Like what you see? Have a play with our trial version.

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
titleJava
collapsetrue
package rest.code.examples;
import java.io.IOException;
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;
/**
 * Create a user using the Yellowfin REST API
 */
public class CreateSSOTokenWithAccessToken {
    public static void main(String[] args) throws Exception {

        String host = "http://localhost:8080/Yellowfin";
        String restUsername = "admin@yellowfin.com.au";
        String restPassword = "test";

        String userToLogin = "user1@yellowfin.com.au";
        String userToLoginPassword = "test";

        String createUserPayload = "{\n"
                + "  \"signOnUser\": {\n"
                + "    \"userName\": \""+ userToLogin + "\",\n"
                + "    \"password\": \""+ userToLoginPassword + "\"\n"
                + "  }\n"
                + "}";

        String token = generateToken(host, restUsername, restPassword);

        System.out.println("Payload: " + createUserPayload);

        Content c = Request.post(host + "/api/login-tokens")
                .addHeader("Authorization", "YELLOWFIN ts=" + System.currentTimeMillis() + " , nonce=" + new Random().nextLong() + ", token=" + token)
                .addHeader("Accept", "application/vnd.yellowfin.api-v1+json")
                .addHeader("Content-Type", "application/json")
                .bodyString(createUserPayload, null)
                .execute().returnContent();

        JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
        JsonElement securityToken = jsonObject.get("securityToken");

        System.out.println("SSO Token: " + securityToken);

    }

    public static String generateToken(String host, String username, String password) throws IOException {

        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\": \""+ username + "\",\"password\": \""+ password + "\"}", 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 successfully");
            System.exit(-1);
        }
        return accessToken.getAsString();

    }

}
Code Block
languagec#
titleC#
collapsetrue
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace YellowfinAPIExamples
{
    public class CreateSSOTokenWithAccessToken
    {
        static async Task Main(string[] args)
        {
            string host = "http://localhost:8080/Yellowfin";
            string restUsername = "admin@yellowfin.com.au";
            string restPassword = "test";
            string userToLogin = "user1@yellowfin.com.au";
            string userToLoginPassword = "test";

            string createUserPayload = "{\n"
                + "  \"signOnUser\": {\n"
                + "    \"userName\": \"" + userToLogin + "\",\n"
                + "    \"password\": \"" + userToLoginPassword + "\"\n"
                + "  }\n"
                + "}";

            string token = await GenerateToken(host, restUsername, restPassword);

            Console.WriteLine("Payload: " + createUserPayload);

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("YELLOWFIN", "ts=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + " , nonce=" + new Random().NextInt64() + ", token=" + token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.yellowfin.api-v1+json"));

                var content = new StringContent(createUserPayload, System.Text.Encoding.UTF8, "application/json");

                HttpResponseMessage response = await httpClient.PostAsync(host + "/api/login-tokens", content);
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseBody);
                    string securityToken = jsonObject["securityToken"].ToString();
                    Console.WriteLine("SSO Token: " + securityToken);
                }
                else
                {
                    Console.WriteLine("Failed to create SSO token. Status code: " + response.StatusCode);
                }
            }
        }

        static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
        {
            using (var client = new HttpClient())
            {
                long nonce = new Random().NextInt64();

                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 }),
                    System.Text.Encoding.UTF8,
                    "application/json"
                );

                HttpResponseMessage response = await client.SendAsync(request);
                string responseContent = await response.Content.ReadAsStringAsync();

                JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
                string accessToken = jsonObject["_embedded"]["accessToken"]["securityToken"].ToString();

                if (!string.IsNullOrEmpty(accessToken))
                {
                    Console.WriteLine("Access Token: " + accessToken);
                    return accessToken;
                }
                else
                {
                    Console.WriteLine("Token not retrieved successfully");
                    Environment.Exit(-1);
                }
            }

            return null; // Should not reach here due to Environment.Exit
        }
    }
}
Code Block
titleGo
collapsetrue
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"time"
)

func main() {
	host := "http://localhost:8080/Yellowfin"
	restUsername := "admin@yellowfin.com.au"
	restPassword := "test"

	userToLogin := "user1@yellowfin.com.au"
	userToLoginPassword := "test"

	createUserPayload := fmt.Sprintf(`{
		"signOnUser": {
			"userName": "%s",
			"password": "%s"
		}
	}`, userToLogin, userToLoginPassword)

	token, err := generateToken(host, restUsername, restPassword)
	if err != nil {
		fmt.Println("Error generating token:", err)
		return
	}

	fmt.Println("Payload:", createUserPayload)

	client := &http.Client{}
	req, err := http.NewRequest("POST", host+"/api/login-tokens", bytes.NewBuffer([]byte(createUserPayload)))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	nonce := rand.Int63()

	req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d, token=%s", time.Now().UnixMilli(), nonce, token))
	req.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json")
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	var jsonObject map[string]interface{}
	err = json.Unmarshal(body, &jsonObject)
	if err != nil {
		fmt.Println("Error parsing JSON response:", err)
		return
	}

	securityToken, ok := jsonObject["securityToken"].(string)
	if !ok {
		fmt.Println("Token not retrieved successfully")
		return
	}

	fmt.Println("SSO Token:", securityToken)
}

func generateToken(host, restUsername, restPassword string) (string, error) {
	nonce := rand.Int63()

	requestBody, err := json.Marshal(map[string]string{
		"userName": restUsername,
		"password": restPassword,
	})
	if err != nil {
		fmt.Println("Error marshaling request body:", err)
		return "", err
	}

	client := &http.Client{}

	request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return "", err
	}

	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")

	response, err := client.Do(request)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return "", err
	}
	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return "", err
	}

	var jsonResponse map[string]interface{}
	err = json.Unmarshal(responseBody, &jsonResponse)
	if err != nil {
		fmt.Println("Error parsing JSON response:", err)
		return "", err
	}

	accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
	if !ok {
		fmt.Println("Token not retrieved successfully")
		return "", fmt.Errorf("Token not retrieved successfully")
	}

	return accessToken, nil
}

...

Code Block
languagejava
titleJava
collapsetrue
package rest.code.examples;
import java.io.IOException;
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;
/**
 * Create a SSO login token for use with a tenant using the Yellowfin REST API
 */
public class CreateSSOTokenWithAccessTokenIntoTenant {
    public static void main(String[] args) throws Exception {

        String host = "http://localhost:8080/Yellowfin";
        String restUsername = "admin@yellowfin.com.au";
        String restPassword = "test";

        String userToLogin = "user1@yellowfin.com.au";
        String userToLoginPassword = "test";
        String clientOrgReference = "CLIENT1";

        String createUserPayload = "{\n"
                + "  \"signOnUser\": {\n"
                + "    \"userName\": \""+ userToLogin + "\",\n"
                + "    \"password\": \""+ userToLoginPassword + "\",\n"
                + "    \"clientOrgRef\": \""+ clientOrgReference + "\"\n"
                + "  }\n"
                + "}";

        String token = generateToken(host, restUsername, restPassword);

        System.out.println("Payload: " + createUserPayload);

        Content c = Request.post(host + "/api/login-tokens")
                .addHeader("Authorization", "YELLOWFIN ts=" + System.currentTimeMillis() + " , nonce=" + new Random().nextLong() + ", token=" + token)
                .addHeader("Accept", "application/vnd.yellowfin.api-v1+json")
                .addHeader("Content-Type", "application/json")
                .bodyString(createUserPayload, null)
                .execute().returnContent();

        JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
        JsonElement securityToken = jsonObject.get("securityToken");

        System.out.println("SSO Token: " + securityToken);

    }

    public static String generateToken(String host, String username, String password) throws IOException {

        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\": \""+ username + "\",\"password\": \""+ password + "\"}", 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 successfully");
            System.exit(-1);
        }
        return accessToken.getAsString();

    }

}
Code Block
languagec#
titleC#
collapsetrue
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace YellowfinAPIExamples
{
    public class CreateSSOTokenWithAccessTokenIntoTenant
    {
        static async Task Main(string[] args)
        {
            string host = "http://localhost:8080/Yellowfin";
            string restUsername = "admin@yellowfin.com.au";
            string restPassword = "test";
            string userToLogin = "user1@yellowfin.com.au";
            string userToLoginPassword = "test";
            string clientOrgReference = "CLIENT1";

            string createUserPayload = "{\n"
                                       + "  \"signOnUser\": {\n"
                                       + "    \"userName\": \"" + userToLogin + "\",\n"
                                       + "    \"password\": \"" + userToLoginPassword + "\",\n"
                                       + "    \"clientOrgRef\": \"" + clientOrgReference + "\"\n"
                                       + "  }\n"
                                       + "}";

            string token = await GenerateToken(host, restUsername, restPassword);

            Console.WriteLine("Payload: " + createUserPayload);

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("YELLOWFIN", "ts=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + " , nonce=" + new Random().NextInt64() + ", token=" + token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.yellowfin.api-v1+json"));

                var content = new StringContent(createUserPayload, System.Text.Encoding.UTF8, "application/json");

                HttpResponseMessage response = await httpClient.PostAsync(host + "/api/login-tokens", content);
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseBody);
                    string securityToken = jsonObject["securityToken"].ToString();
                    Console.WriteLine("SSO Token: " + securityToken);
                }
                else
                {
                    Console.WriteLine("Failed to create SSO token. Status code: " + response.StatusCode);
                }
            }
        }

        static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
        {
            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 }),
                    System.Text.Encoding.UTF8,
                    "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");
                    Environment.Exit(-1);
                }

                return accessToken;
            }
        }
    }
}
Code Block
titleGo
collapsetrue
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"time"
)

func main() {
	host := "http://localhost:8080/Yellowfin"
	restUsername := "admin@yellowfin.com.au"
	restPassword := "test"

	userToLogin := "user1@yellowfin.com.au"
	userToLoginPassword := "test"
	clientOrgReference := "CLIENT1"

	createUserPayload := `{
  "signOnUser": {
    "userName": "` + userToLogin + `",
    "password": "` + userToLoginPassword + `",
    "clientOrgRef": "` + clientOrgReference + `"
  }
}`

	token, err := generateToken(host, restUsername, restPassword)
	if err != nil {
		fmt.Println("Error generating token:", err)
		return
	}

	fmt.Println("Payload:", createUserPayload)

	nonce := rand.Int63()

	req, err := http.NewRequest("POST", host+"/api/login-tokens", bytes.NewBuffer([]byte(createUserPayload)))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d, token=%s", time.Now().UnixMilli(), nonce, token))
	req.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json")
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	var jsonResponse map[string]interface{}
	err = json.Unmarshal(body, &jsonResponse)
	if err != nil {
		fmt.Println("Error parsing JSON response:", err)
		return
	}

	securityToken, ok := jsonResponse["securityToken"].(string)
	if !ok {
		fmt.Println("SSO Token not retrieved")
		return
	}

	fmt.Println("SSO Token:", securityToken)
}

func generateToken(host, restUsername, restPassword string) (string, error) {
	nonce := rand.Int63()

	requestBody, err := json.Marshal(map[string]string{
		"userName": restUsername,
		"password": restPassword,
	})
	if err != nil {
		fmt.Println("Error marshaling request body:", err)
		return "", err
	}

	client := &http.Client{}

	request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return "", err
	}

	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")

	response, err := client.Do(request)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return "", err
	}
	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return "", err
	}

	var jsonResponse map[string]interface{}
	err = json.Unmarshal(responseBody, &jsonResponse)
	if err != nil {
		fmt.Println("Error parsing JSON response:", err)
		return "", err
	}

	accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
	if !ok {
		fmt.Println("Token not retrieved")
		return "", fmt.Errorf("Token not retrieved successfully")
	}

	return accessToken, nil
}

...

Code Block
languagejava
titleJava
collapsetrue
package rest.code.examples;
import java.io.IOException;
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;
/**
 * Create a targeted SSO login token using the Yellowfin REST API
 */
public class CreateSSOTokenWithAccessTokenToPage {
    public static void main(String[] args) throws Exception {

        String host = "http://localhost:8080/Yellowfin";
        String restUsername = "admin@yellowfin.com.au";
        String restPassword = "test";

        String userToLogin = "user1@yellowfin.com.au";
        String userToLoginPassword = "test";
        String entryDashboardUUID = "321e5a85-a349-4cfb-b8f4-c9141059a66a";

        String createUserPayload = "{\n"
                + "  \"signOnUser\": {\n"
                + "    \"userName\": \""+ userToLogin + "\",\n"
                + "    \"password\": \""+ userToLoginPassword + "\"\n"
                + "  },\n"
                + "   \"loginParameters\": ["
                + "   \"ENTRY=VIEWDASHBOARD\","
                + "\"DASHBOARDUUID=" + entryDashboardUUID + "\""
                + " ] "
                + "}";

        String token = generateToken(host, restUsername, restPassword);

        System.out.println("Payload: " + createUserPayload);

        Content c = Request.post(host + "/api/login-tokens")
                .addHeader("Authorization", "YELLOWFIN ts=" + System.currentTimeMillis() + " , nonce=" + new Random().nextLong() + ", token=" + token)
                .addHeader("Accept", "application/vnd.yellowfin.api-v1+json")
                .addHeader("Content-Type", "application/json")
                .bodyString(createUserPayload, null)
                .execute().returnContent();

        JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
        JsonElement securityToken = jsonObject.get("securityToken");

        System.out.println("SSO Token: " + securityToken);

    }

    public static String generateToken(String host, String username, String password) throws IOException {

        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\": \""+ username + "\",\"password\": \""+ password + "\"}", 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 successfully");
            System.exit(-1);
        }
        return accessToken.getAsString();

    }

}
Code Block
languagec#
titleC#
collapsetrue
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace YellowfinAPIExamples
{
    public class CreateSSOTokenWithAccessTokenToPage
    {
        static async Task Main(string[] args)
        {
            string host = "http://localhost:8080/Yellowfin";
            string restUsername = "admin@yellowfin.com.au";
            string restPassword = "test";
            string userToLogin = "user1@yellowfin.com.au";
            string userToLoginPassword = "test";
            string entryDashboardUUID = "321e5a85-a349-4cfb-b8f4-c9141059a66a";

            string createUserPayload = "{\n"
                + "  \"signOnUser\": {\n"
                + "    \"userName\": \"" + userToLogin + "\",\n"
                + "    \"password\": \"" + userToLoginPassword + "\"\n"
                + "  },\n"
                + "   \"loginParameters\": ["
                + "   \"ENTRY=VIEWDASHBOARD\","
                + "\"DASHBOARDUUID=" + entryDashboardUUID + "\""
                + " ] "
                + "}";

            string token = await GenerateToken(host, restUsername, restPassword);

            Console.WriteLine("Payload: " + createUserPayload);

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("YELLOWFIN", "ts=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + " , nonce=" + new Random().NextInt64() + ", token=" + token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.yellowfin.api-v1+json"));

                var content = new StringContent(createUserPayload, System.Text.Encoding.UTF8, "application/json");

                HttpResponseMessage response = await httpClient.PostAsync(host + "/api/login-tokens", content);
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseBody);
                    string securityToken = jsonObject["securityToken"].ToString();
                    Console.WriteLine("SSO Token: " + securityToken);
                }
                else
                {
                    Console.WriteLine("Failed to create SSO token. Status code: " + response.StatusCode);
                }
            }
        }

        static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
        {
            using (var client = new HttpClient())
            {
                long nonce = new Random().NextInt64();

                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 }),
                    System.Text.Encoding.UTF8,
                    "application/json"
                );

                HttpResponseMessage response = await client.SendAsync(request);
                string responseContent = await response.Content.ReadAsStringAsync();

                JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
                string accessToken = jsonObject["_embedded"]["accessToken"]["securityToken"].ToString();

                if (!string.IsNullOrEmpty(accessToken))
                {
                    Console.WriteLine("Access Token: " + accessToken);
                    return accessToken;
                }
                else
                {
                    Console.WriteLine("Token not retrieved successfully");
                    Environment.Exit(-1);
                }
            }

            return null; // Should not reach here due to Environment.Exit
        }
    }
}
Code Block
titleGo
collapsetrue
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"time"
)

func main() {
	host := "http://localhost:8080/Yellowfin"
	restUsername := "admin@yellowfin.com.au"
	restPassword := "test"

	userToLogin := "user1@yellowfin.com.au"
	userToLoginPassword := "test"
	entryDashboardUUID := "321e5a85-a349-4cfb-b8f4-c9141059a66a"

	createUserPayload := fmt.Sprintf(`{
		"signOnUser": {
			"userName": "%s",
			"password": "%s",
			"loginParameters": [
				"ENTRY=VIEWDASHBOARD",
				"DASHBOARDUUID=%s"
			]
		}
	}`, userToLogin, userToLoginPassword, entryDashboardUUID)

	token, err := generateToken(host, restUsername, restPassword)
	if err != nil {
		fmt.Println("Error generating token:", err)
		return
	}

	fmt.Println("Payload:", createUserPayload)

	client := &http.Client{}
	req, err := http.NewRequest("POST", host+"/api/login-tokens", bytes.NewBuffer([]byte(createUserPayload)))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	nonce := rand.Int63()

	req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d, token=%s", time.Now().UnixMilli(), nonce, token))
	req.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json")
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	var jsonObject map[string]interface{}
	err = json.Unmarshal(body, &jsonObject)
	if err != nil {
		fmt.Println("Error parsing JSON response:", err)
		return
	}

	securityToken, ok := jsonObject["securityToken"].(string)
	if !ok {
		fmt.Println("Token not retrieved successfully")
		return
	}

	fmt.Println("SSO Token:", securityToken)
}

func generateToken(host, restUsername, restPassword string) (string, error) {
	nonce := rand.Int63()

	requestBody, err := json.Marshal(map[string]string{
		"userName": restUsername,
		"password": restPassword,
	})
	if err != nil {
		fmt.Println("Error marshaling request body:", err)
		return "", err
	}

	client := &http.Client{}

	request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return "", err
	}

	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")

	response, err := client.Do(request)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return "", err
	}
	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return "", err
	}

	var jsonResponse map[string]interface{}
	err = json.Unmarshal(responseBody, &jsonResponse)
	if err != nil {
		fmt.Println("Error parsing JSON response:", err)
		return "", err
	}

	accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
	if !ok {
		fmt.Println("Token not retrieved successfully")
		return "", fmt.Errorf("Token not retrieved successfully")
	}

	return accessToken, nil
}

...

Code Block
languagejava
titleJava
collapsetrue
package rest.code.examples;
import java.io.IOException;
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;
/**
 * Create a SSO login token without a user's password using the Yellowfin REST API
 */
public class CreateSSOTokenWithAccessTokenNoPassword {
    public static void main(String[] args) throws Exception {

        System.out.println("SSO Login User without a password");

        String host = "http://localhost:8080/Yellowfin";
        String restUsername = "admin@yellowfin.com.au";
        String restPassword = "test";

        String userToLogin = "user1@yellowfin.com.au";

        String createUserPayload = "{\n"
                + "  \"signOnUser\": {\n"
                + "    \"userName\": \""+ userToLogin + "\"\n"
                + "  },\n"
                + " \"noPassword\": true \n"
                + "}";

        String token = generateToken(host, restUsername, restPassword);

        System.out.println("Payload: " + createUserPayload);

        Content c = Request.post(host + "/api/login-tokens")
                .addHeader("Authorization", "YELLOWFIN ts=" + System.currentTimeMillis() + " , nonce=" + new Random().nextLong() + ", token=" + token)
                .addHeader("Accept", "application/vnd.yellowfin.api-v1+json")
                .addHeader("Content-Type", "application/json")
                .bodyString(createUserPayload, null)
                .execute().returnContent();

        JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
        JsonElement securityToken = jsonObject.get("securityToken");

        System.out.println("SSO Token: " + securityToken);

    }

    public static String generateToken(String host, String username, String password) throws IOException {

        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\": \""+ username + "\",\"password\": \""+ password + "\"}", 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 successfully");
            System.exit(-1);
        }
        return accessToken.getAsString();

    }

}
Code Block
languagec#
titleC#
collapsetrue
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace YellowfinAPIExamples
{
    public class CreateSSOTokenWithAccessTokenNoPassword
    {
        static async Task Main(string[] args)
        {
            string host = "http://localhost:8080/Yellowfin";
            string restUsername = "admin@yellowfin.com.au";
            string restPassword = "test";
            string userToLogin = "user1@yellowfin.com.au";

            string createUserPayload = "{\n"
                + "  \"signOnUser\": {\n"
                + "    \"userName\": \"" + userToLogin + "\",\n"
                + "  },\n"
                + "  \"noPassword\": true\n"
                + "}";

            string token = await GenerateToken(host, restUsername, restPassword);

            Console.WriteLine("Payload: " + createUserPayload);

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("YELLOWFIN", "ts=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + " , nonce=" + new Random().NextInt64() + ", token=" + token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.yellowfin.api-v1+json"));

                var content = new StringContent(createUserPayload, System.Text.Encoding.UTF8, "application/json");

                HttpResponseMessage response = await httpClient.PostAsync(host + "/api/login-tokens", content);
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseBody);
                    string securityToken = jsonObject["securityToken"].ToString();
                    Console.WriteLine("SSO Token: " + securityToken);
                }
                else
                {
                    Console.WriteLine("Failed to create SSO token. Status code: " + response.StatusCode);
                }
            }
        }

        static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
        {
            using (var client = new HttpClient())
            {
                long nonce = new Random().NextInt64();

                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 }),
                    System.Text.Encoding.UTF8,
                    "application/json"
                );

                HttpResponseMessage response = await client.SendAsync(request);
                string responseContent = await response.Content.ReadAsStringAsync();

                JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
                string accessToken = jsonObject["_embedded"]["accessToken"]["securityToken"].ToString();

                if (!string.IsNullOrEmpty(accessToken))
                {
                    Console.WriteLine("Access Token: " + accessToken);
                    return accessToken;
                }
                else
                {
                    Console.WriteLine("Token not retrieved successfully");
                    Environment.Exit(-1);
                }
            }

            return null; // Should not reach here due to Environment.Exit
        }
    }
}
Code Block
titleGo
collapsetrue
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "math/rand"
    "net/http"
    "time"
)

func main() {
	host := "http://localhost:8080/Yellowfin"
    restUsername := "admin@yellowfin.com.au"
    restPassword := "test"

    userToLogin := "user1@yellowfin.com.au"

    createUserPayload := fmt.Sprintf(`{
        "signOnUser": {
            "userName": "%s"
        },
        "noPassword": true
	}`, userToLogin)
	
	token, err := generateToken(host, restUsername, restPassword)
	if err != nil {
		fmt.Println("Error generating token:", err)
		return
	}

	fmt.Println("Payload:", createUserPayload)

	client := &http.Client{}
	req, err := http.NewRequest("POST", host+"/api/login-tokens", bytes.NewBuffer([]byte(createUserPayload)))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	nonce := rand.Int63()

	req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d, token=%s", time.Now().UnixMilli(), nonce, token))
	req.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json")
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	var jsonObject map[string]interface{}
	err = json.Unmarshal(body, &jsonObject)
	if err != nil {
		fmt.Println("Error parsing JSON response:", err)
		return
	}

	securityToken, ok := jsonObject["securityToken"].(string)
	if !ok {
		fmt.Println("Token not retrieved successfully")
		return
	}

	fmt.Println("SSO Token:", securityToken)
}

func generateToken(host, restUsername, restPassword string) (string, error) {
	nonce := rand.Int63()

	requestBody, err := json.Marshal(map[string]string{
        "userName": restUsername,
        "password": restPassword,
	})
	if err != nil {
		fmt.Println("Error marshaling request body:", err)
		return "", err
	}

	client := &http.Client{}

	request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return "", err
	}

	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")

	response, err := client.Do(request)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return "", err
	}
	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return "", err
	}

	var jsonResponse map[string]interface{}
	err = json.Unmarshal(responseBody, &jsonResponse)
	if err != nil {
		fmt.Println("Error parsing JSON response:", err)
		return "", err
	}

	accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
	if !ok {
		fmt.Println("Token not retrieved successfully")
		return "", fmt.Errorf("Token not retrieved successfully")
	}

	return accessToken, nil
}

...

Code Block
languagejava
titleJava
collapsetrue
package rest.code.examples;
import java.io.IOException;
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;
/**
 * Destroy a SSO session using the Yellowfin REST API
 */
public class DestroySSOSession {
    public static void main(String[] args) throws Exception {

        String host = "http://localhost:8080/Yellowfin";
        String restUsername = "admin@yellowfin.com.au";
        String restPassword = "test";

        // This is a loginTokenId from the initial REST call to receive a securityToken for SSO
        String loginTokenId = "ac69b491-26cc-c399-7e59-2e441c9e1433";

        String token = generateToken(host, restUsername, restPassword);

        Content c = Request.delete(host + "/api/login-tokens/" + loginTokenId)
                .addHeader("Authorization", "YELLOWFIN ts=" + System.currentTimeMillis() + " , nonce=" + new Random().nextLong() + ", token=" + token)
                .addHeader("Accept", "application/vnd.yellowfin.api-v1+json")
                .addHeader("Content-Type", "application/json")
                .execute().returnContent();
        System.out.println(c.toString());

    }

    public static String generateToken(String host, String username, String password) throws IOException {

        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\": \""+ username + "\",\"password\": \""+ password + "\"}", 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 successfully");
            System.exit(-1);
        }
        return accessToken.getAsString();

    }

}

...

Code Block
titleGo
collapsetrue
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "math/rand"
    "net/http"
    "time"
)

func main() {
	host := "http://localhost:8080/Yellowfin"
    restUsername := "admin@yellowfin.com.au"
    restPassword := "test"
    loginTokenID := "ac69b491-26cc-c399-7e59-2e441c9e1433"

    token, err := generateToken(host, restUsername, restPassword)
	if err != nil {
		fmt.Println("Error generating token:", err)
		return
	}

	fmt.Println("Deleting login token:", loginTokenID)

	client := &http.Client{}
	req, err := http.NewRequest("DELETE", host+"/api/login-tokens/"+loginTokenID, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	nonce := rand.Int63()

	req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d, token=%s", time.Now().UnixMilli(), nonce, token))
	req.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json")
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	fmt.Println(string(body))
}

func generateToken(host, username, password string) (string, error) {
	// Generate nonce
	nonce := rand.Int63()

	// Create request body
	requestBody, err := json.Marshal(map[string]string{
        "userName": username,
        "password": password,
	})
	if err != nil {
		fmt.Println("Error marshaling request body:", err)
		return "", err
	}

	// 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 "", err
	}

	// 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 {
		fmt.Println("Error sending request:", err)
		return "", err
	}
	defer response.Body.Close()

	// Read response body
	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return "", err
	}

	// Parse JSON response
	var jsonResponse map[string]interface{}
	err = json.Unmarshal(responseBody, &jsonResponse)
	if err != nil {
		fmt.Println("Error parsing JSON response:", err)
		return "", err
	}

	// Get access token from response
	accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
	if !ok {
		fmt.Println("Token not retrieved")
		return "", fmt.Errorf("Token not retrieved successfully")
	}

	return accessToken, nil
}

...