JWT 기반 보안
상태를 저장하지 않는 API를 위해 JSON 웹 토큰(JWT)을 사용한 토큰 기반 인증을 구현합니다.
JWT 기반 보안은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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.,
issfor issuer,expfor expiration,subfor 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:
- Generates a JWT.
- Sends the JWT back to the client.
For subsequent requests, the client:
- Stores the JWT (e.g., in local storage).
- Attaches the JWT in the
Authorizationheader (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 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
“JWT 기반 보안”에서 뭘 배우나요?
상태를 저장하지 않는 API를 위해 JSON 웹 토큰(JWT)을 사용한 토큰 기반 인증을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“JWT 기반 보안” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.