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

Генерирует токен аутентификации доступа для указанного пользователя, чтобы использовать функциональность встроенного контента.

Метод

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

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

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

Имя

userCredentials

Тип объекта

UserCredentials

Описание

Объект учётных данных пользователя, используемый для задания настроек входа пользователя.

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

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

200

Тип ответа

string

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

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

Примечания

Токен безопасности — это строка, которую нужно добавить в cookie на странице стороннего узла, где размещён встраиваемый контент, чтобы доступ был авторизован.

Примеры

Аутентификация пользователя для встраивания (C#):

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

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 Default : System.Web.UI.Page { public const String API_PATH = “http://mySite.com/API3/"; protected void Page_Load(object sender, EventArgs e) {

		//logging the user for embed
		String adminTokenEmbed = getToken("authenticateUserEmbed", new
		{ 	
			userName = "adminUser1",
			password = "abc123!",
			domain = "myEmbedSite.com"
		});

		//alternative embed using the admim user token (so not requiring the user's password)
		String userTokenEmbed = getToken("authenticateUserEmbedByToken", new
		{ 	
			userIdentity = "userName",
			token = adminTokenEmbed
		});<br><br>			//this cookie should be applied at myEmbedSite.com, assuming myEmbedSite.com is installed on a different domain
		Response.Cookies.Add(new HttpCookie("PyramidEmbeddedAuth", userTokenEmbed));
	}

//generic method for getting the token via REST
	private String getToken(String service, Object data)
	{
		HttpClient client = new HttpClient();

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

		return response.Result.Content.ReadAsStringAsync().Result;
	}
	
	//generic method for running 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&gt;HttpResponseMessage&lt; response = client.PostAsync(API_PATH + service, content);

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

}

	</code></pre></details>

	<details><summary>Аутентификация пользователя для встраивания (Java):</summary><p>В этом примере показано, как выполнить аутентификацию пользователей для встраивания.</p><pre class="line-numbers"><code class="language-java">import com.sun.net.httpserver.HttpExchange;

import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.json.simple.JSONObject;

import java.io.IOException; import java.net.InetSocketAddress;

public class Main { private static final String pyramidPath = “http://mySite.com/API3/";

public static void main(String[] args) throws IOException {
	HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
	server.createContext("/embed", new EmbedHandler());

	server.setExecutor(null); // creates a default executor
	server.start();

}

private static class EmbedHandler implements HttpHandler {
	@Override
	public void handle(HttpExchange httpExchange) throws IOException {
		//logging the user
		JSONObject adminCredentials = new JSONObject();
		adminCredentials.put("userName", "adminUser1");
		adminCredentials.put("password", "abc123!");
		adminCredentials.put("domain", "myEmbedSite.com");
		String adminToken = getToken("authenticateUserEmbed", adminCredentials);

		//getting user's embed token using the admin's authenctication token
		JSONObject userCredentials = new JSONObject();
		adminCredentials.put("userIdentity", "JohnSmith");
		adminCredentials.put("token", adminToken);
		String userToken = getToken("authenticateUserEmbedByToken", userCredentials);

		//setting the cookie PyramidEmbeddedAuth to userToken
		byte[] message = "you logged in".getBytes();
		httpExchange.getResponseHeaders().add("Set-Cookie", "PyramidEmbeddedAuth=" + userToken);
		httpExchange.sendResponseHeaders(200, -1);
		httpExchange.getResponseBody().write(message);
		httpExchange.close();
	}
}

protected static String getToken(String service, JSONObject data) throws IOException {
	return sendPost("authentication/" + service, data.toJSONString());
}

protected static String sendPost(String path, String data) throws IOException {
	try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

		String address = pyramidPath + path;
		HttpPost request = new HttpPost(address);
		StringEntity params = new StringEntity(data);
		request.addHeader("content-type", "application/x-www-form-urlencoded");
		request.setEntity(params);
		CloseableHttpResponse response = httpClient.execute(request);
		return new BasicResponseHandler().handleResponse(response);
	}
}

}

	</code></pre></details>

Примеры кода

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/authenticateUserEmbed" \
 -d '{
  "password" : "password",
  "domain" : "domain",
  "customData" : "customData",
  "username" : "username"
}'
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 userCredentials parameter object for the call
        UserCredentials userCredentials = ; // Create the input object for the operation, type: UserCredentials 

        try {
            String result = apiInstance.authenticateUserEmbed(userCredentials);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling AuthenticationServiceApi#authenticateUserEmbed");
            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 userCredentials = ; // {UserCredentials} 

api.authenticateUserEmbed(userCredentials).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 authenticateUserEmbedExample
{
    public static void Main()
    {
        Configuration conf = new Configuration();
        conf.BasePath = "http://Your.Server.URL/";
        
        
        GlobalConfiguration.Instance = conf;
        
        // Create an instance of the API class
        var apiInstance = new AuthenticationServiceApi();
        // Initialize the userCredentials parameter object for the call
        var userCredentials = new UserCredentials(); // UserCredentials | 

        try {
            // Generates an access authentication token for the given user to use the embedded content functionality.
            string result = apiInstance.authenticateUserEmbed(userCredentials);
            Debug.WriteLine(result);
        } catch (Exception e) {
            Debug.Print("Exception when calling AuthenticationServiceApi.authenticateUserEmbed: " + 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 userCredentials parameter object for the call
    userCredentials =  # UserCredentials | 

    try:
        # Generates an access authentication token for the given user to use the embedded content functionality.
        api_response = api_instance.authenticate_user_embed(userCredentials)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling AuthenticationServiceApi->authenticateUserEmbed: %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();
$userCredentials = ; // UserCredentials | 

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