Authentification de l'API Web JSON

Consultez la section /auth de la documentation WebAPI pour obtenir des informations complètes sur les méthodes d'authentification de l'API Web du compteur eGauge.

L'API Web eGauge utilise l'authentification par jeton Web JSON (JWT) pour toutes les interactions. Un en-tête « Authorization » doit être fourni avec les requêtes API Web au format Authorization: Bearer JWT où JWT est un jeton Web JSON valide.

Les jetons expirent généralement après 10 minutes et doivent être renouvelés périodiquement.

Il existe deux méthodes pour obtenir un jeton :

  • Objet Digest : Il s’agit de la méthode recommandée pour obtenir un JWT, décrite dans ce document. Cette méthode est similaire à la méthode d’authentification HTTP Digest.
  • Objet Mot de passe : Cette méthode transmet les identifiants en clair et nécessite donc une connexion sécurisée, par exemple HTTPS, à l’adresse IP locale du compteur. Une erreur sera renvoyée si l’opération est tentée via le serveur proxy eGauge, même avec HTTPS.


Vous trouverez plus d'informations sur les méthodes d'authentification en cliquant sur l'objet que vous souhaitez utiliser dans la section /auth de la documentation WebAPI :

Exemple : Utilisez le volet de navigation à gauche pour développer les menus des points de terminaison.

Flux de travail d'authentification Digest


Étape 1 : Envoyer une requête GET à /auth/unauthorized pour obtenir une erreur 401 afin d’obtenir le domaine ( rlm ) et le nonce du serveur ( nnc ).

Étape 2 : Générer un nonce client ( cnnc )

Étape 3 : Calculer le hachage au format :

ha1 = MD5(usr:rlm:pwd)
hash = MD5(ha1:nnc:cnnc)
où usr et pwd sont un nom d'utilisateur et un mot de passe valides sur le compteur.

Étape 4 : Envoyez rlm , usr , nnc , cnnc et hash à /auth/login pour obtenir le jeton.

Authentification Digest en Python

eGauge Systems propose une bibliothèque Python contenant des fonctions d'assistance pour la gestion de l'authentification et autres interactions. Consultez la page d'introduction à l'API Web pour plus d'informations.

#!/usr/bin/env python3
# Example Python script obtaining a JSON web token (JWT) from a meter's WebAPI.
# JWTs are needed for any interactions with the meter's JSON-based WebAPI.
# eGauge provides a Python library that handles authentication automatically and
# provides additional helper functions. It may be found on Bitbucket or PyPi
# https://bitbucket.org/egauge/python/src/master/egauge/
# https://pypi.org/project/egauge-python/
# Main WebAPI documentation: https://egauge.net/support/webapi
import requests
import hashlib
from secrets import token_hex
# meter and credential information
URI = "https://eGauge67385.d.egauge.net"
USER = "admin"
PASS = "as$kS2345da2@4vK9"

# get realm (rlm) and server nonce (nnc):
auth_req = requests.get(f"{URI}/api/auth/unauthorized").json()
realm = auth_req["rlm"]
nnc = auth_req["nnc"]
cnnc = str(token_hex(64)) # generate a client nonce (cnnc)
# generate our hash
# ha1 = MD5(usr:rlm:pwd)
# hash = MD5(ha1:nnc:cnnc)
ha1_content = f"{USER}:{realm}:{PASS}"
ha1 = hashlib.md5(ha1_content.encode("utf-8")).hexdigest()
hash_content = f"{ha1}:{nnc}:{cnnc}"
hash = hashlib.md5(hash_content.encode("utf-8")).hexdigest()
# Generate our payload
payload = {
   "rlm": realm,
   "usr": USER,
   "nnc": nnc,
   "cnnc": cnnc,
   "hash": hash
}
# POST to /auth/login to get a JWT
auth_login = requests.post(f"{URI}/api/auth/login", json=payload).json()
rights = auth_login["rights"] # rights this token has (save, control, etc)
jwt = auth_login["jwt"] # the actual bearer token
print(f"Got token with rights {rights}.")
# We can verify this token works.
# Add an authorization header with our token and make a request
headers = {"Authorization": f"Bearer {jwt}"}
api_request = requests.get(
   f"{URI}/api/config/net/hostname",
   headers=headers,
)
# {'result': 'eGauge67385'}
print(api_request.json())
# This token may be used until it expires, in which case a 401 response will be
# returned, to which this process can be reperformed.

Authentification Digest avec Bash

Ce script bash utilise curl et jq pour obtenir un JWT à utiliser avec l'API Web.

URI="https://eGauge67385.d.egauge.net"
USER="admin"
PASS="as$kS2345da2@4vK9"
auth_req=$(curl -s "$URI/api/auth/unauthorized")
rlm=$(jq -r '.rlm' <<< $auth_req)
nnc=$(jq -r '.nnc' <<< $auth_req)
cnnc=$(openssl rand -hex 64)
ha1=$(echo -n "$USER:$rlm:$PASS" | md5sum | cut -f1 -d" ")
hash=$(echo -n "$ha1:$nnc:$cnnc" | md5sum | cut -f1 -d" ")
auth_login=$(curl -s -X POST "$URI/api/auth/login" \
    -H "Content-Type: application/json" \
    -d "{\"rlm\": \"$rlm\", \"usr\": \"$USER\", \"nnc\": \"$nnc\", \"cnnc\": \"$cnnc\", \"hash\": \"$hash\"}")
jwt=$(jq -r '.jwt' <<< $auth_login)
api_request=$(curl -s "$URI/api/config/net/hostname" -H "Authorization: Bearer $jwt")
echo $api_request