Аутентификация пользователя для встраивания с использованием проверки подлинности Windows

Генерирует токен аутентификации доступа Дельта BI для встраивания по токенам проверки подлинности Windows

Метод

/API3/authentication/authenticateUserEmbedWindows
  • Раздел API: /API3/authentication
  • Версия API: 3.0
  • Начиная с релиза: 2023.10
  • Использование: REST API и клиентские библиотеки SDK. REST API — только через POST-запросы.
  • Кто использует:
    • Enterprise Admin
    • Domain Admin
    • Pro
    • Analyst
    • Viewer
    • Basic

Сигнатура метода

Входные параметры

Имя

domain

Тип

string

Описание

Веб-домен URL — нужен только для аутентификации для встраивания.

Выходной ответ

Код успешного результата

200

Тип ответа

string

Описание типа ответа

Ответ представляет собой токен безопасности в виде строки base64. Обычно он сохраняется в cookie.

Примечания

Токен безопасности — это строка, которую нужно добавить в cookie на странице стороннего узла, где размещён встраиваемый контент, чтобы доступ был авторизован. Веб-браузер должен поддерживать проверку подлинности Windows (Windows Authentication), а МЕТОД аутентификации в Дельта BI должен быть установлен в «Windows Authentication». В настоящее время этот метод не поддерживается в SDK Дельта BI, кроме вариантов REST и C#.

Примеры

Клиентская/API-аутентификация пользователя (C#):

В этом примере показано, как выполнить аутентификацию пользователей с проверкой подлинности Windows (Windows Authentication) и программно выполнить запрос.

using System;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace CsWebSite { public partial class WinAuth : System.Web.UI.Page { public const String API_PATH = “http://mySite.com/api3/"; protected void Page_Load(object sender, EventArgs e) { //logging the current user with windows auth String userToken = getToken(“authenticateUserWindows”, null);

		Response.Cookies.Add(new HttpCookie("PyramidAuth", userToken));

		//running a query. The user needs to be an admin user to access this API.
		JToken result = callApi("analytics/extractQueryResult", new
		{
			itemId= "9185ea22-bf14-4606-a955-4bbd73a88c38", //content items ID
			exportType =0,//export result as json, we can do xml(1) and CSV(2) as well
			exportOptions=new
			{
				showUniqueName=true
			}
		},userToken);
		//the result is passed as a json string, needed to be deserialized again to read the values
		JToken document = JsonConvert.DeserializeObject>JObject<(result.ToString());
		String firstResult = document["Document"]["queries"][0]["result"]["data"][0][0].ToString();
	}

	//this method is diffrent then the normal to pass windows credentals UseDefaultCredentials=true
	private String getToken(String service, Object data)
	{
		HttpClient client = new HttpClient(new HttpClientHandler()
		{
			UseDefaultCredentials = true
		});

		StringContent content = null;
		content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
		Task<HttpResponseMessage> response = client.PostAsync(API_PATH + "authentication/" + service, content);

		return response.Result.Content.ReadAsStringAsync().Result;
	}
	
	//generic method for calling REST methods
	private JToken callApi(String service, Object data, String token)
	{
		HttpClient client = new HttpClient();
		client.DefaultRequestHeaders.Add("paToken", token);

		StringContent content = null;
		content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
		Task>HttpResponseMessage< response = client.PostAsync(API_PATH + service, content);

		String resultStr = response.Result.Content.ReadAsStringAsync().Result;
		if (resultStr.Count() == 0)
		{
			return null;
		}
		return JsonConvert.DeserializeObject>JObject<(resultStr)["data"];
	}
}

}

Примеры кода

TypeScript

Curl

Java

C#

Python

PHP

curl -X POST \
 -H "Accept: text/plain,text/plain;charset=utf-8" \
 -H "Content-Type: application/json" \
 "http://Your.Server.URL/API3/authentication/authenticateUserEmbedWindows" \
 -d ''
import com.pyramidanalytics.*;
import com.pyramidanalytics.auth.*;
import com.pyramidanalytics.model.*;
import com.pyramidanalytics.api.AuthenticationServiceApi;

import java.util.*;
import java.time.*;

public class AuthenticationServiceApiExample {
    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();
        defaultClient.setBasePath("http://Your.Server.URL/");

        // Create an instance of the API class
        AuthenticationServiceApi apiInstance = new AuthenticationServiceApi();
        // Initialize the domain parameter object for the call
        String domain = domain_example; // Create the input object for the operation, type: String 

        try {
            String result = apiInstance.authenticateUserEmbedWindows(domain);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling AuthenticationServiceApi#authenticateUserEmbedWindows");
            e.printStackTrace();
        }
    }
}
import * as PyramidAnalyticsWebApi from "com.pyramidanalytics";

// Create an instance of the API class
const api = new PyramidAnalyticsWebApi.AuthenticationServiceApi("http://Your.Server.URL")

const domain = domain_example; // {String} 

api.authenticateUserEmbedWindows(domain).then(function(data) {
  console.log('API called successfully. Returned data: ' + data);
}, function(error) {
  console.error(error);
});
using System;
using System.Diagnostics;
using PyramidAnalytics.Sdk.Api;
using PyramidAnalytics.Sdk.Client;
using PyramidAnalytics.Sdk.Model;

public class authenticateUserEmbedWindowsExample
{
    public static void Main()
    {
        Configuration conf = new Configuration();
        conf.BasePath = "http://Your.Server.URL/";
        conf.UseDefaultCredentials = true; // allow sending windows credentials in the request
        
        GlobalConfiguration.Instance = conf;
        
        // Create an instance of the API class
        var apiInstance = new AuthenticationServiceApi();
        // Initialize the domain parameter object for the call
        var domain = domain_example;  // Create the input object for the operation, type: String | 

        try {
            // Generates a Pyramid access authentication token for embedding using Windows Authentication tokens
            string result = apiInstance.authenticateUserEmbedWindows(domain);
            Debug.WriteLine(result);
        } catch (Exception e) {
            Debug.Print("Exception when calling AuthenticationServiceApi.authenticateUserEmbedWindows: " + e.Message );
        }
    }
}
import com.pyramidanalytics
from com.pyramidanalytics import ApiException
from com.pyramidanalytics import AuthenticationServiceApi
from pprint import pprint

    api_config = com.pyramidanalytics.Configuration(host = 'http://Your.Server.URL')

with com.pyramidanalytics.ApiClient(api_config) as api_client:
    # Create an instance of the API class
    api_instance = AuthenticationServiceApi(api_client)
    # Initialize the domain parameter object for the call
    domain = domain_example # String | 

    try:
        # Generates a Pyramid access authentication token for embedding using Windows Authentication tokens
        api_response = api_instance.authenticate_user_embed_windows(domain)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling AuthenticationServiceApi->authenticateUserEmbedWindows: %s\n" % e)
<?php
require_once(__DIR__ . '/vendor/autoload.php');

OpenAPITools\Client\Configuration::getDefaultConfiguration()->setHost('http://Your.Server.URL');

// Create an instance of the API class
$api_instance = new OpenAPITools\Client\Api\AuthenticationServiceApi();
$domain = domain_example; // String | 

try {
    $result = $api_instance->authenticateUserEmbedWindows($domain);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling AuthenticationServiceApi->authenticateUserEmbedWindows: ', $e->getMessage(), PHP_EOL;
}
?>