0Pricing
AI Powered SaaS: Stripe + Auth + Billing + Deploy · Урок

Вход и создание JWT

Создайте систему входа пользователей, которая выпускает и обрабатывает токены JSON Web Token (JWT) для управления сеансами.

«Вход и создание JWT» — бесплатный урок AI Powered SaaS: Stripe + Auth + Billing + Deploy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения AI Powered SaaS: Stripe + Auth + Billing + Deploy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс AI Powered SaaS: Stripe + Auth + Billing + Deploy содержит 4 уроков всего.

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

Welcome to Login Systems

In the previous lesson, we learned about user registration and secure password hashing. Now, it's time to build the login system!

A login system allows authenticated users to access protected resources and personalize their experience within your SaaS application.

How Login Works (Overview)

When a user tries to log in, they typically provide a username (or email) and a password. Here's the basic flow:

  • The client (e.g., your mobile app) sends credentials to the server.
  • The server verifies these credentials against its stored user data.
  • If valid, the server grants access.

Verifying User Credentials

Upon receiving login credentials, your server needs to perform a crucial check:

  1. Find the user by their unique identifier (e.g., email or username).
  2. Retrieve the stored hashed password for that user.
  3. Compare the provided password (after hashing it with the same method) with the stored hashed password.

Never store passwords in plain text! Always hash and salt them, as we discussed in the registration lesson.

The Challenge: Stateless APIs

Modern APIs are often stateless, meaning the server doesn't remember previous requests from the same client. This makes APIs scalable but poses a challenge for user authentication.

How do we know if a user who just logged in is still authenticated on their next request without sending credentials every time?

Introducing JSON Web Tokens (JWT)

JSON Web Tokens (JWTs) are a compact, URL-safe means of representing claims to be transferred between two parties. They are perfect for stateless authentication.

Instead of server-side sessions, the server issues a JWT upon successful login. The client then stores this token and sends it with every subsequent request.

JWT Structure: Header

A JWT consists of three parts separated by dots: Header, Payload, and Signature.

The Header typically contains two parts:

  • typ (type of token, usually 'JWT')
  • alg (signing algorithm, e.g., 'HS256' for HMAC SHA256)

It's a JSON object, Base64Url-encoded.

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

JWT Structure: Payload (Claims)

The Payload contains the 'claims' – statements about an entity (usually the user) and additional data.

Claims can be:

  • Registered: Standard fields like sub (subject), exp (expiration time), iat (issued at time).
  • Public: Custom claims defined by you, but registered in the IANA JSON Web Token Registry.
  • Private: Custom claims agreed upon by the parties using them, like userId or role.

Example Payload:

{"sub":"12345","name":"Coddy User","exp":1700000000}

JWT Structure: Signature

The Signature is crucial for verifying the token's integrity. It's created by taking the encoded header, the encoded payload, and a secret key, then applying the algorithm specified in the header.

If anyone tries to tamper with the header or payload, the signature verification will fail, making the token invalid. The secret key is known only to the server.

Generating a JWT (Conceptual)

After successfully verifying a user's credentials, your server generates a JWT. This involves:

  1. Creating the Header and Payload JSON objects.
  2. Base64Url-encoding both.
  3. Concatenating them with a dot.
  4. Signing the combined string using a secret key and the chosen algorithm to produce the Signature.

The final JWT is EncodedHeader.EncodedPayload.Signature.

JWT Generation Example

While full JWT signing requires a library, we can demonstrate the Base64 encoding part of building a JWT string. This ensures the token is URL-safe.

import java.util.Base64;
import java.nio.charset.StandardCharsets;

public class Main {
  public static void main(String[] args) {
    String headerJson = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
    String payloadJson = "{\"sub\":\"user123\",\"name\":\"Coddy User\"}";

    String encodedHeader = Base64.getUrlEncoder().withoutPadding().encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
    String encodedPayload = Base64.getUrlEncoder().withoutPadding().encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8));

    System.out.println("Header (Base64Url-encoded):\n" + encodedHeader);
    System.out.println("\nPayload (Base64Url-encoded):\n" + encodedPayload);
    System.out.println("\nConceptual JWT structure: " + encodedHeader + "." + encodedPayload + ".[Signature]");
  }
}

Quick Check: JWT Parts

You've just learned about the three main parts of a JSON Web Token (JWT).

Recap: Login & JWTs

Great job! You've learned how a user login system works and the role of JSON Web Tokens (JWTs) in modern, stateless authentication.

  • Login involves verifying credentials against hashed passwords.
  • JWTs provide a stateless way to manage user sessions.
  • JWTs have three parts: Header, Payload, and Signature.
  • The Signature ensures the token's integrity.

Next, we'll explore how to use these JWTs to protect your API routes!

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

Урок «Вход и создание JWT» бесплатный?

Да — полный текст урока «Вход и создание JWT» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс AI Powered SaaS: Stripe + Auth + Billing + Deploy, подпишись на CoddyKit PRO. Курс AI Powered SaaS: Stripe + Auth + Billing + Deploy содержит 4 уроков всего.

Чему я научусь в уроке «Вход и создание JWT»?

Создайте систему входа пользователей, которая выпускает и обрабатывает токены JSON Web Token (JWT) для управления сеансами. Ты практикуешь AI Powered SaaS: Stripe + Auth + Billing + Deploy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Предыдущий опыт не требуется. AI Powered SaaS: Stripe + Auth + Billing + Deploy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

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

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

Можно ли писать и запускать код в этом уроке AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Да. Каждый урок AI Powered SaaS: Stripe + Auth + Billing + Deploy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

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

  1. Регистрация пользователей и хеширование
  2. Вход и создание JWT
  3. Защищённые маршруты и промежуточное ПО
  4. Сброс пароля и подтверждение электронной почты
← Назад к AI Powered SaaS: Stripe + Auth + Billing + Deploy