Структура и подпись токена ID
Разберите заголовок, полезную нагрузку и подпись токена ID (JWT), выяснив, как он подписывается и какую информацию содержит.
«Структура и подпись токена ID» — бесплатный урок OAuth2 & OpenID Connect Deep Dive на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения OAuth2 & OpenID Connect Deep Dive, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс OAuth2 & OpenID Connect Deep Dive содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Meet the ID Token
In OpenID Connect (OIDC), the ID Token is a crucial piece of information. It's a security token that contains claims about the authentication of an end-user by an Authorization Server.
Think of it as a digital ID card for the user, issued after they successfully log in.
ID Tokens Are JWTs
ID Tokens are always formatted as JSON Web Tokens (JWTs). A JWT is a compact, URL-safe means of representing claims to be transferred between two parties.
Every JWT has three main parts, separated by dots:
- Header
- Payload
- Signature
The Header: What Algorithm?
The first part of an ID Token is the Header. It's a JSON object that describes the token itself, like what type of token it is and the algorithm used to sign it.
alg: The cryptographic algorithm used for signing (e.g., RS256, HS256).typ: The type of token, which is usually"JWT".
Header in Action
When you decode the base64url-encoded header, you'll see a JSON object like this. This tells you how the token was secured.
{
"alg": "RS256",
"typ": "JWT",
"kid": "someKeyId"
}The kid (Key ID) helps find the correct public key for verification.
Decoding Header Example
The header is base64url encoded. Here's how you might decode a JWT header string in Java. This helps reveal its content.
import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class JwtDecoder {
public static void main(String[] args) {
String encodedHeader = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6InNvbWVLZXlJZCJ9";
byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedHeader);
String decodedString = new String(decodedBytes, StandardCharsets.UTF_8);
System.out.println("Decoded Header:");
System.out.println(decodedString);
}
}The Payload: Claims About You
The second part is the Payload. This is where the actual "claims" about the user and the authentication event are stored. Claims are statements about an entity (typically the user).
Standard claims you'll often see include:
iss: Issuer (who issued the token).sub: Subject (unique identifier for the user).aud: Audience (who the token is for).exp: Expiration Time (when the token expires).iat: Issued At Time (when the token was issued).
Payload in Action
Similar to the header, the payload is also a base64url-encoded JSON object. It contains the identity information you need.
{
"iss": "https://example.com/auth",
"sub": "user123",
"aud": "myAppClientId",
"exp": 1678886400,
"iat": 1678882800,
"name": "Alice Wonderland"
}exp and iat are Unix timestamps.
The Signature: Ensuring Trust
The third and final part is the Signature. This is critical for security! It's used to verify that the token hasn't been tampered with and that it comes from a legitimate issuer.
The signature is created by taking the encoded header, the encoded payload, and a secret key or private key, and running them through the cryptographic algorithm specified in the header.
Verifying the Signature
When your application receives an ID Token, it uses the public key (provided by the Issuer) to verify the signature. It re-computes the signature using the header, payload, and the public key.
If the re-computed signature matches the token's signature, you can trust that:
- The token hasn't been altered.
- It was issued by the expected Authorization Server.
Quick Check on JWT
You've learned that ID Tokens are structured as JWTs, with three distinct parts. Each part plays a vital role in conveying and securing user identity information.
Recap: ID Token Anatomy
Great job! You now understand the fundamental structure of an ID Token.
- Header: Describes the token and signing algorithm.
- Payload: Contains identity claims about the user.
- Signature: Ensures the token's integrity and authenticity.
Each part is base64url encoded and separated by dots, forming a secure and verifiable digital identity for the user.
Часто задаваемые вопросы
Урок «Структура и подпись токена ID» бесплатный?
Да — полный текст урока «Структура и подпись токена ID» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс OAuth2 & OpenID Connect Deep Dive, подпишись на CoddyKit PRO. Курс OAuth2 & OpenID Connect Deep Dive содержит 4 уроков всего.
Чему я научусь в уроке «Структура и подпись токена ID»?
Разберите заголовок, полезную нагрузку и подпись токена ID (JWT), выяснив, как он подписывается и какую информацию содержит. Ты практикуешь OAuth2 & OpenID Connect Deep Dive с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать OAuth2 & OpenID Connect Deep Dive?
Предыдущий опыт не требуется. OAuth2 & OpenID Connect Deep Dive на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Структура и подпись токена ID»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке OAuth2 & OpenID Connect Deep Dive?
Да. Каждый урок OAuth2 & OpenID Connect Deep Dive включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Структура и подпись токена ID
- JWS и наборы JWK
- Отзыв и интроспекция токенов
- Проверка стандартных утверждений ID-токена