Todentaminen (authentication) ja oikeuksien hallinta (authorization).

  • Päivitetty

Todentaminen ja oikeuksien hallinta perustuvat Authorization-otsakkeeseen sekä muihin pyyntöotsakkeisiin. Jokaiselle pyynnölle on laskettava erillinen allekirjoitus, joka on osa Authorization-otsaketta.

Pyyntöjen tekemiseen tarvitset seuraavat asennuskohtaiset tiedot. Mikäli ne puuttuvat, ota yhteys Liana Technologiesin yhteyshenkilöösi:

  • API User ID
  • API Secret
  • API Realm
  • API Url


Vaaditut otsakkeet 

Jotta jokainen pyyntö onnistuisi, vaadimme seuraavat otsakkeet:
 

Oikeuksien hallinta (authorization)

Oikeuksien hallinta valtuutetaan Authorization-otsakkeella. Tämä otsake koostuu kolmesta osasta:

  • Realm: Realm on suuraakkosista koostuva merkkijono, joka määritetään LianaAutomation-asennuksesi verkkotunnuksen (domain) perusteella.

  • User id: Tämä on API-käyttäjäsi yksilöllinen tunniste (ja se toimii vain yhdessä asennuksessa).

  • Signature: Signature (allekirjoitus), joka lasketaan muiden muuttujien avulla (selitetty alla).

Osat yhdistetään seuraavasti:

{Realm} {User id}:{Signature}

Esimerkki Authorization-otsakkeesta

Authorization: LCUI 1:d79ffb8112a62fb8af166cedfb96164ee7d2f3d6fea9669cd3b40f52ca69692f


Date 

Date-otsakkeen on sisällettävä aikaleima tietokoneen luettavassa muodossa. ISO 8601 -standardin käyttö on suositeltavaa. Aikaleima saa olla enintään 15 minuuttia vanha. Voit esimerkiksi lähettää useita pyyntöjä käyttäen samaa aikaleimaa 15 minuutin ajan.

Esimerkki Date-otsakkeesta:

Date: 2021-09-14T15:28:09+03:00


Content-md5

 Tämä otsake sisältää pyynnön rungon (request body) MD5-hash.

Esimerkki Content-md5-otsakkeesta:

Content-md5: 344aab9758bb0d018b93739e7893fb3a


Content-Type

Pyyntöjen sisällön (payload) tyypin on oltava application/json.

Esimerkki Content-Type-otsakkeesta:

Content-Type: application/json

Signature

Signature Authorization-otsakkeen Signature (allekirjoitus) generoidaan käyttämällä HMAC-SHA256-algoritmia. HMAC-avaimena käytetään REST-käyttäjän salasanaa, ja viesti (message) muodostetaan seuraavasti:

Luo UTF-8-muotoinen merkkijono käyttäen UNIX-tyylisiä rivinvaihtoja (\n). Lisää merkkijonoon seuraavat tiedot, kukin omalle rivilleen:

  • Request method: Metodi on POST kaikissa rajapintapisteissämme (endpoints).

  • Content-md5: Content-md5-otsakkeen arvo.

  • Content-Type: Content-Type-otsakkeen arvo.

  • Date: Date-otsakkeen arvo.

  • Content: Pyynnön koko sisältö (request body).

  • PATH: URI-osoitteen polkuosa (path), mukaan lukien mahdolliset kyselyparametrit (query parameters).

Esimerkki:

POST
344aab9758bb0d018b93739e7893fb3a
application/json
2021-09-14T15:28:09+03:00
{"ping":"pong"}
/rest/v1/pingpong

signaturecontent = POST\n344aab9758bb0d018b93739e7893fb3a\napplication/json\n2021-09-14T15:28:09+03:00\n{"ping":"pong"}\n/rest/v1/pingpong
   
HMAC_SHA256("password", signaturecontent)
= d79ffb8112a62fb8af166cedfb96164ee7d2f3d6fea9669cd3b40f52ca69692f

 

Koodiesimerkit 

Koodiesimerkit yhteyden testaamiseksi voit käyttää mitä tahansa alla olevista koodiesimerkeistä, jotka hyödyntävät pingpong-päätepistettämme (endpoint).

PHP 

<?php

/**
 * Account specific variables.
 *
 * These variables are given to you by or can be requested from your contact person at Liana Technologies.
 */
$user   = "USER ID";          // The user id, integer
$secret = "USER SECRET";      // An hexadecimal secret string
$url    = "REST API URL";     // The base url for your API installation
$realm  = "REST API REALM";   // The realm of your API installation, all caps alphanumeric string

/**
 * General variables
 */
$basePath    = 'rest';             // Base path of the api end points
$contentType = 'application/json'; // Content will be send as json
$method      = 'POST';             // Method is always POST

/**
 * Send a API request to LianaAutomation
 *
 * This function will add the required headers and calculates the signature for the authorization header
 *
 * @param string $path             The path of the end point
 * @param array  $data             The content body (data) of the request
 * @return mixed
 */
function send(string $path, array $data) {
	// Import variables
	global $user, $secret, $url, $realm, $basePath, $contentType, $method;
	// Encode our body content data
	$data = json_encode($data);
	// Get the current datetime in ISO 8601
	$date = date('c');
	// md5 hash our body content
	$contentMd5 = md5($data);
	// Create our signature
	$signatureContent = implode(
		"\n",
		[
			$method,
			$contentMd5,
			$contentType,
			$date,
			$data,
			"/{$basePath}/{$path}"
		],
	);
	$signature = hash_hmac('sha256', $signatureContent, $secret);
	// Create the authorization header value
	$auth = "{$realm} {$user}:" . $signature;

	// Create our full stream context with all required headers
	$ctx = stream_context_create([
		'http' => [
			'method' => $method,
			'header' => implode(
				"\r\n",
				[
					"Authorization: {$auth}",
					"Date: {$date}",
					"Content-md5: {$contentMd5}",
					"Content-Type: {$contentType}"
				]
			),
			'content' => $data
		]
	]);

	// Build full path, open a data stream, and decode the json response
	$fullPath = "{$url}/{$basePath}/{$path}";
	$fp = fopen($fullPath, 'rb', false, $ctx);
	$response = stream_get_contents($fp);
	$response = json_decode($response, true);
	return $response;
}

// Example usage:
$a = send(
	'v1/pingpong',
	[
		'ping' => 'pong'
	]
);
var_dump($a);

Node (JavaScript) 

/**
 * Dependencies
 *
 * We use the CryptoJS library for hashing and fetch for making the http call
 */
import md5 from 'crypto-js/md5.js';
import hmacSHA256 from 'crypto-js/hmac-sha256.js';
import fetch from 'node-fetch';

/**
 * Account specific variables.
 *
 * These variables are given to you by or can be requested from your contact person at Liana Technologies.
 */
var user   = "USER ID";          // The user id, integer
var secret = "USER SECRET";      // An hexadecimal secret string
var url    = "REST API URL";     // The base url for your API installation
var realm  = "REST API REALM";   // The realm of your API installation, all caps alphanumeric string

/**
 * General variables
 */
var basePath    = 'rest';             // Base path of the api end points
var contentType = 'application/json'; // Content will be send as json
var method      = 'POST';             // Method is always POST

async function send(path, data) {
	// Format object to string
	data = JSON.stringify(data);
	// Get the current datetime in ISO 8601
	let date = new Date().toISOString();
	// md5 hash our body content
	let contentMd5 = md5(data).toString();
	// Create our signature
	let signatureContent = [
		method,
		contentMd5,
		contentType,
		date,
		data,
		'/' + basePath + '/' + path
	].join('\n');
	let signature = hmacSHA256(signatureContent, secret).toString();

	// Create the authorization header value
	let auth = realm + ' ' + user + ':' + signature;

	// Build the full path and create our request with all required headers
	let fullPath = url + '/' + basePath + '/' + path;
	let response = await fetch(fullPath, {
		"method": method,
		"headers": {
			"Authorization": auth,
			"Date": date,
			"Content-md5": contentMd5,
			"Content-Type": contentType
		},
		"body": data
	});

	// Return the response
	return response.json().then(res => {
		return res;
	});
}

// Example usage
send('v1/pingpong', {"ping":"pong"}).then((data) => {
	console.log(data);
});

Postman

Voit käyttää myös Postmania Authorization-otsakkeen muodostamiseen.

  • Luo uusi Collection (kokoelma)
  • Sijoita alla oleva skripti kokoelman ‘Pre-request Script’ -välilehdelle
  • Lisää vaaditut muuttujat kokoelman ‘Variables’-välilehdelle
  • Luo uusi POST-pyyntö sinulle annettuun API-URL-osoitteeseen, jonka loppuosa on /rest/v1/pingpong
  • Käytä {"ping":"pong"} rungon (body) sisältönä. Varmista, että sisällön tyypiksi on valittu raw ja muodoksi JSON
Pre-Request Script 
/**
 * - Create a new collection to paste this script as Pre-request Script
 * - Set following account specific variables in the Variables tab of your Collection.
 *   These variables are given to you by or can be requested from your contact person at Liana Technologies.
 * user
 * secret
 * realm
 */

// General variables
var contentType = 'application/json';

// Dynamically fetched variables from the request
var method = pm.request.method.toUpperCase();
var data = pm.request.body.toString();
var path = pm.request.url.getPath();

// Get the current datetime in ISO 8601
var date = new Date().toISOString();
// md5 hash our body content
var contentMd5 = CryptoJS.MD5(data).toString();

// Create our signature
var signatureContent = [
	method,
	contentMd5,
	contentType,
	date,
	data,
	path
].join('\n');
var signature = CryptoJS.HmacSHA256(signatureContent, pm.variables.get("secret")).toString();
// Create the authorization header value
var auth = pm.variables.replaceIn("{{realm}} {{user}}:") + signature;

// Add headers
pm.request.headers.add({
	key: "Authorization",
	value: auth
});
pm.request.headers.add({
	key: "Date",
	value: date
});
pm.request.headers.add({
	 key: "Content-md5",
	 value: contentMd5
});

 

 
 

 

 

Oliko tämä artikkeli hyödyllinen?

0/0 koki tästä olevan apua

Kommentit

0 kommenttia

Kommentointi on poistettu käytöstä.