0Pricing
AI Powered SaaS: Stripe + Auth + Billing + Deploy · 강의

로그인 및 JWT 생성

세션 관리를 위해 JSON 웹 토큰(JWT)을 발급하고 관리하는 사용자 로그인 시스템을 구축합니다.

로그인 및 JWT 생성은(는) CoddyKit의 무료 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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 튜터), CoddyKit PRO로 업그레이드하면 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의 전체를 잠금 해제할 수 있습니다. AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에는 총 4개의 강의가 포함되어 있습니다.

“로그인 및 JWT 생성”에서 뭘 배우나요?

세션 관리를 위해 JSON 웹 토큰(JWT)을 발급하고 관리하는 사용자 로그인 시스템을 구축합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Powered SaaS: Stripe + Auth + Billing + Deploy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Powered SaaS: Stripe + Auth + Billing + Deploy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Powered SaaS: Stripe + Auth + Billing + Deploy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“로그인 및 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(으)로 돌아가기