0Pricing
Spring Boot 4 Complete Guide · Урок

Безопасность на основе JWT

Реализуйте аутентификацию на основе токенов с использованием JSON Web Tokens (JWT) для API без состояния

«Безопасность на основе JWT» — бесплатный урок Spring Boot 4 Complete Guide на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Complete Guide, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Complete Guide содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Intro to JWT-Based Security

Welcome to the final lesson on Spring Security! Today, we'll explore JSON Web Tokens (JWTs), a popular method for securing stateless APIs.

Unlike traditional session-based authentication, JWTs allow the server to remain stateless, making them ideal for microservices and mobile applications.

What is a JWT?

A JWT is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object.

  • Compact: Small size, can be sent through URL, POST parameter, or inside an HTTP header.
  • Self-contained: Contains all necessary information about the user, avoiding database lookups for every request.

Anatomy of a JWT

A JWT consists of three parts, separated by dots (.):

  • Header
  • Payload
  • Signature

It typically looks like: xxxxx.yyyyy.zzzzz

The Header: Algorithm & Type

The Header usually consists of two parts: the type of the token (which is JWT) and the signing algorithm being used (e.g., HS256 or RS256).

This JSON is then Base64Url-encoded to form the first part of the JWT.

{"alg":"HS256","typ":"JWT"}

The Payload: Claims

The Payload contains the 'claims' – statements about an entity (typically, the user) and additional data. There are three types of claims:

  • Registered claims: Standard, non-mandatory claims (e.g., iss for issuer, exp for expiration, sub for subject).
  • Public claims: Defined by users, require collision-resistant names.
  • Private claims: Custom claims agreed upon by sender and receiver.

The Signature: Trust & Integrity

The Signature is created by taking the encoded header, the encoded payload, a secret key, and the algorithm specified in the header. It ensures the token hasn't been tampered with.

If someone changes the header or payload, the signature verification will fail, making the token invalid. The secret key must be kept confidential!

Generating JWT Parts (Code)

Let's see how the header and payload are Base64Url-encoded. The signature would then be computed using these encoded parts and a secret.

import java.util.Base64;

public class JwtPartsDemo {
  public static void main(String[] args) {
    String headerJson = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
    String payloadJson = "{\"sub\":\"coddyUser\",\"iat\":1678886400,\"exp\":1678890000}";
    
    String encodedHeader = Base64.getUrlEncoder().withoutPadding().encodeToString(headerJson.getBytes());
    String encodedPayload = Base64.getUrlEncoder().withoutPadding().encodeToString(payloadJson.getBytes());
    
    System.out.println("Encoded Header: " + encodedHeader);
    System.out.println("Encoded Payload: " + encodedPayload);
    System.out.println("\nJWT format: EncodedHeader.EncodedPayload.Signature");
  }
}

JWT Flow in Spring Security

When a user successfully authenticates (e.g., logs in with username/password), the server:

  1. Generates a JWT.
  2. Sends the JWT back to the client.

For subsequent requests, the client:

  1. Stores the JWT (e.g., in local storage).
  2. Attaches the JWT in the Authorization header (e.g., Bearer YOUR_TOKEN).

The server then intercepts and validates this token for each protected request.

Validating JWTs (Code Concept)

A custom filter in Spring Security would extract the token, decode its parts, and then critically, verify the signature and validate claims like expiration.

import java.util.Base64;

public class JwtValidationDemo {
  public static void main(String[] args) {
    // A simplified example token (signature part is placeholder)
    String jwtToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjb2RkeVVzZXIiLCJpYXQiOjE2Nzg4ODY0MDAsImV4cCI6MTY3ODg5MDAwMH0.SIGNATURE_PLACEHOLDER";
    
    String[] parts = jwtToken.split("\\.");
    
    if (parts.length == 3) {
      String decodedHeader = new String(Base64.getUrlDecoder().decode(parts[0]));
      String decodedPayload = new String(Base64.getUrlDecoder().decode(parts[1]));
      
      System.out.println("Decoded Header: " + decodedHeader);
      System.out.println("Decoded Payload: " + decodedPayload);
      
      // In a real application, you would:
      // 1. Verify the 'SIGNATURE_PLACEHOLDER' using the secret key.
      // 2. Parse 'decodedPayload' JSON to check claims like 'exp' (expiration).
      if (decodedPayload.contains("\"sub\":\"coddyUser\"")) {
        System.out.println("Payload contains expected subject 'coddyUser'.");
      }
    } else {
      System.out.println("Invalid JWT format.");
    }
  }
}

Quick Check: JWT Parts

Based on what we've learned, which of the following are standard parts of a JSON Web Token (JWT) that are transmitted?

Recap: JWT-Based Security

In this lesson, we explored JWT-based security, understanding its three key parts: Header, Payload, and Signature.

We learned how JWTs enable stateless authentication, making them highly scalable and suitable for modern APIs and mobile applications. You also saw conceptual code examples for generating and validating JWTs.

This concludes our Spring Security course! You've learned to secure applications from basic authentication to advanced token-based systems.

Часто задаваемые вопросы

Урок «Безопасность на основе JWT» бесплатный?

Да — полный текст урока «Безопасность на основе JWT» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Complete Guide, подпишись на CoddyKit PRO. Курс Spring Boot 4 Complete Guide содержит 4 уроков всего.

Чему я научусь в уроке «Безопасность на основе JWT»?

Реализуйте аутентификацию на основе токенов с использованием JSON Web Tokens (JWT) для API без состояния Ты практикуешь Spring Boot 4 Complete Guide с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Boot 4 Complete Guide?

Предыдущий опыт не требуется. Spring Boot 4 Complete Guide на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Безопасность на основе JWT»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Boot 4 Complete Guide?

Да. Каждый урок Spring Boot 4 Complete Guide включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Основы Spring Security
  2. Аутентификация и авторизация
  3. Безопасность на основе JWT
  4. Интеграция OAuth2 и входа через социальные сети
← Назад к Spring Boot 4 Complete Guide