Vés al contingut

JSON Web Token

De la Viquipèdia, l'enciclopèdia lliure
Aquesta és una versió anterior d'aquesta pàgina, de data 23:15, 4 nov 2021 amb l'última edició de Techi2ee (discussió | contribucions). Pot tenir inexactituds o contingut no apropiat no present en la versió actual.
(dif.) ←la pròxima versió més antiga | vegeu la versió actual (dif.) | Versió més nova → (dif.)


JSON Web Token (JWT) és un estàndard obert que permet l'intercanvi de testimonis d'autenticació (tokens) en arquitectures client-servidor. Es fa en format JSON, en un entorn web, de forma segura i per verificar la identitat o el rol de l'usuari a la part client.

Per exemple, un client s'identifica com administrador en la seva interacció amb el servidor, que genera un testimoni i li retorna al client. En endavant, el client el podrà enviar en totes les comunicacions per provar que efectivament, té drets d'administrador. Els successius cops que el servidor el rep, mirarà al seu repositori de testimonis per comprovar amb quin rol ha de tractar la invocació.

Estructura

Capçalera
{
  "alg": "HS256",
  "typ": "JWT"
}
Identifica l'algorisme amb què ha estat generada la signatura

HS256 indica que aquest testimoni és signat usant HMAC-SHA256.

El més típic és usar els algorismes HMAC amb SHA-256 (HS256) i Signatura RSA amb SHA-256 (RS256).

JWA (JSON Web Algorithms) RFC 7518 n'introdueix més Tant per autenticació com xifrat.

Cos
{
  "identificacio": "admin",
  "hora": 1422779638
}
Contains a set of claims. The JWT specification defines seven Registered Claim Names which are the standard fields commonly included in tokens. Custom claims are usually also included, depending on the purpose of the token.

This example has the standard Issued At Time claim (iat) and a custom claim (loggedInAs).

Signatura
HMAC_SHA256(
  secret,
  base64urlEncoding(capcalera) + '.' +
  base64urlEncoding(cos)
)
Securely validates the token. The signature is calculated by encoding the header and payload using Base64url Encoding RFC 4648 and concatenating the two together with a period separator. That string is then run through the cryptographic algorithm specified in the header, in this case HMAC-SHA256. The Base64url Encoding is similar to base64, but uses different non-alphanumeric characters and omits padding.

The three parts are encoded separately using Base64url Encoding RFC 4648, and concatenated using periods to produce the JWT:

const token = base64urlEncoding(header) + '.' + base64urlEncoding(payload) + '.' + base64urlEncoding(signature)

The above data and the secret of "secretkey" creates the token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI

This resulting token can be easily passed into HTML and HTTP.