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

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

Метод

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

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

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

Имя

userTokenCredentials

Тип объекта

UserTokenCredentials

Описание

Учётные данные пользователя для аутентификации по токену.

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

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

200

Тип ответа

string

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

Ответ представляет собой токен безопасности в виде строки base64. Обычно он сохраняется в 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/authenticateUserEmbedByToken" \
 -d '{
  "domain" : "domain",
  "customData" : "customData",
  "userIdentity" : "userIdentity",
  "token" : "token"
}'
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 userTokenCredentials parameter object for the call
        UserTokenCredentials userTokenCredentials = ; // Create the input object for the operation, type: UserTokenCredentials 

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

api.authenticateUserEmbedByToken(userTokenCredentials).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 authenticateUserEmbedByTokenExample
{
    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 userTokenCredentials parameter object for the call
        var userTokenCredentials = new UserTokenCredentials(); // UserTokenCredentials | 

        try {
            // Generates an access authentication token for embedding content, for a given user without their password, using an administrative token.
            string result = apiInstance.authenticateUserEmbedByToken(userTokenCredentials);
            Debug.WriteLine(result);
        } catch (Exception e) {
            Debug.Print("Exception when calling AuthenticationServiceApi.authenticateUserEmbedByToken: " + 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 userTokenCredentials parameter object for the call
    userTokenCredentials =  # UserTokenCredentials | 

    try:
        # Generates an access authentication token for embedding content, for a given user without their password, using an administrative token.
        api_response = api_instance.authenticate_user_embed_by_token(userTokenCredentials)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling AuthenticationServiceApi->authenticateUserEmbedByToken: %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();
$userTokenCredentials = ; // UserTokenCredentials | 

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