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

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

Метод

/API2/auth/authenticateUserEmbedByToken
  • Раздел API: /API2/auth
  • Версия API: 2.0
  • Начиная с релиза: 2018.5
  • Использование: только 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/API2/"; protected void Page_Load(object sender, EventArgs e) {

		//logging the user for embed
		String adminTokenEmbed = getToken("authenticateUserEmbed", new
		{ 	data = 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 { data = new { userIdentity = “userName”, token = adminTokenEmbed } });

//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<HttpResponseMessage> response = client.PostAsync(API_PATH + "auth/" + 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();

		StringContent content = null;
		data = new { auth = token, data = data };
		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"];
	}
}

}

	</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/API2/";

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 {
	JSONObject dataHolder = new JSONObject();
	dataHolder.put("data", data);
	return sendPost("auth/" + service, dataHolder.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>