Authentification pour l’API Clearance

Guide du développeur Genetec Clearance™

Content type
Guides > Guides pour développeurs
Product line
Clearance
ft:locale
fr-FR
Applies to
Clearance

L'authentification est le processus par lequel l'identité d'un utilisateur ou d'une intégration est vérifiée et autorisée. Il existe deux types de mécanismes d'authentification pour Genetec Clearance™, selon qu'il s'agisse d'un utilisateur (OpenID Connect) ou d'une intégration (OAuth2) accédant à l'API. Les deux méthodes d'authentification garantissent la sécurité de vos données Clearance.

Utilisateur depuis un point de navigateur Web

Lorsque vous appelez l’API Clearance directement depuis un navigateur, vous devez toujours utiliser OpenID Connect pour authentifier l’utilisateur, puis utiliser le jeton du porteur dans l’API. L'authentification Clearance utilise automatiquement Azure Active Directory B2B et B2C pour authentifier les utilisateurs.

Demande auprès d'un service back-end

OAuth2 : lorsqu’une autre intégration doit communiquer avec Clearance, nous utilisons une combinaison de clés privées et publiques pour authentifier le service. Les clés sont disponibles dans le fichier de connexion JSON généré après la création d'un compte d'intégration dans Clearance.


Demande de service back-end

Clearance STS (Secure Token Services) est chargé de générer un jeton du porteur JWT qui peut être utilisé dans l'en-tête HTTP de chaque appel d'API REST. Les jetons du porteur ont une date d'expiration et l'appelant est responsable du renouvellement des jetons avant la date d'expiration.

Le client de l'API est responsable du renouvellement du jeton d'accès avant sa date d'expiration. La réponse renvoyée par le point de terminaison du jeton contient les informations nécessaires pour calculer la date d'expiration du jeton d'accès.


Renouvellement STS

Pour obtenir un jeton d'accès, vous devez appeler le point de terminaison /token utilisant le protocole OAUTH2 avec la sous-section RFC7523. Pour ce faire, vous devez utiliser les valeurs contenues dans le fichier de connexion JSON.

  • client_id : la valeur doit être @.

  • grant_type : la valeur doit toujours être urn:ietf:params:oauth:grant-type:jwt-bearer tel que référencé par le RFC7523.

  • assertion : la valeur doit être un jeton Web JSON signé avec la ServicePrincipalKey.

Voici un exemple typique d'appel :

powershell
curl -X POST -d "client_id=<ServicePrincipalId>@<TenantId>&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=<ENTER TOKEN ASSERTION HERE>" https://clearance-a-sts.geneteccloud.com/connect/token

Pour générer une assertion de jeton, vous devez créer un jeton Web JSON et le signer avec la clé fournie dans le fichier de connexion JSON :

csharp
Typescript
python
string clientId = "<ServicePrincipalId>@<TenantId>";
var handler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
  Issuer = clientId,
  SigningCredentials = new SigningCredentials(
    new RsaSecurityKey(... ServicePrincipalKey from config.json ...),   JsonWebKeySignatureAlgorithm.RS256)
};
var token = (JwtSecurityToken)handler.CreateToken(tokenDescriptor);
string tokenAssertion = handler.WriteToken(token);
import jwt = require("jsonwebtoken");
import fetch = require("node-fetch");
import pemjwk = require("pem-jwk");
import { OAuthTokenModel } from "./model/oauthtokenmodel";
import { TenantSettings } from "./model/tenantsettings";

export class OAuth2Client {

    private readonly m_tenantSettings: TenantSettings;

    constructor(tenantSettings: TenantSettings) {
        this.m_tenantSettings = tenantSettings;
    }

    public async getServicePrincipalAccessToken(): Promise<string> {

        const client_id: string = `${this.m_tenantSettings.ServicePrincipalId}@${this.m_tenantSettings.TenantId}`;

        const pemKey = pemjwk.jwk2pem(this.m_tenantSettings.ServicePrincipalKey);
        const now: number = new Date().valueOf() / 1000;
        const requestToken = jwt.sign({ iss: client_id, iat: now, exp: now + (60 * 60), nbf: now}, pemKey, { algorithm: "RS256"});
        const requestModel: OAuthTokenModel = {
            client_id,
            grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
            assertion: requestToken
        };

        const requestInfo: RequestInit = {
            method: "POST",
            body: JSON.stringify(requestModel),
            headers: {
                "Content-Type": "application/json"
            },
        };

        const response = await fetch(`${this.m_tenantSettings.SecurityTokenServiceBaseAddresses[0]}/token`, requestInfo);
        if (response.status === 200) {
            return (await response.json()).access_token;
        }
        throw response.text();
    }
}
import json
import time
from jwcrypto import jwk, jws, jwt
from jwcrypto.common import json_encode
import requests 
import datetime

with open('config.json') as config_json_file:
    data = json.load(config_json_file)
    now = int(time.time()) 
    client_id = data['ServicePrincipalId'] + '@' + data['TenantId']
    expkey = data['ServicePrincipalKey']
    key = jwk.JWK(**expkey)
    token = jwt.JWT(header={"alg": "RS256", "kid": key.key_id},
                    key=key,
                    claims={"iss": client_id, "sub": client_id, "iat": now, "exp": now + (60 * 60), "nbf": now})
    print(token.claims)
    token.make_signed_token(key)
    assertion = token.serialize(True)
    print(assertion)
    r = requests.post(url = data["SecurityTokenServiceBaseAddresses"][0] + "/token",
                      json = {
                        "client_id": client_id,
                        "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
                        "assertion": assertion
                        }) 
    print r.json()["access_token"]

Une fois authentifié, le jeton du porteur JWT doit être inclus dans l'en-tête d'autorisation de chaque requête d'API.

Exemple d'API GET pour une preuve sur le locataire « tenant123 » :

powershell
curl -X GET --header 'Accept: application/json' --header 'Authorization: Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNyc2Etc2hhNTEyIiwia2lkIjoiNzFFODNEMDQ4NjIxMTg0RTMxOENEMDUxREEwMzhBRjQ2MjQ1QTkyMiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiamRveW9uQGdlbmV0ZWMuY29tIiwiaHR0cDovL3NjaGVtYXMuZ2VuZXRlYy5jb20vd3MvMjAxNi8wMy9pZGVudGl0eS9jbGFpbXMvcHJpbWFyeWtpZCI6InVybjp1c2VyOmpkb3lvbmRlbW86amRveW9uQGdlbmV0ZWMuY29tOjMiLCJodHRwOi8vc2NoZW1hcy5nZW5ldGVjLmNvbS93cy8yMDE2LzAzL2lkZW50aXR5L2NsYWltcy9wcmltYXJ5aWQiOiIzIiwiaHR0cDovL3NjaGVtYXMuZ2VuZXRlYy5jb20vd3MvMjAxNi8wMy9pZGVudGl0eS9jbGFpbXMvcHJpbWFyeXR5cGUiOiJ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