การยืนยันตัวตนและการอนุญาตด้วย JWT
ใช้งานการยืนยันตัวตนและการอนุญาตด้วย JWT ภายใน Spring Cloud Gateway เพื่อรักษาความปลอดภัยในการเข้าถึง API
การยืนยันตัวตนและการอนุญาตด้วย JWT เป็นบทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Securing Your API Gateway
In a microservices architecture, securing your APIs is paramount. Spring Cloud Gateway acts as a central entry point, making it the perfect place to enforce security policies.
This lesson focuses on using JSON Web Tokens (JWTs) for both authentication (who is this user?) and authorization (what can this user do?) directly within your Gateway.
Introducing JSON Web Tokens (JWTs)
A JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. It's often used for authentication and information exchange.
- Stateless: The server doesn't need to store session information.
- Self-contained: Contains all the necessary user information and claims.
- Scalable: Easy to use across multiple services without complex session management.
JWT Structure: Header, Payload, Signature
A JWT consists of three parts, separated by dots (.), which are Base64Url-encoded:
- Header: Specifies the token type (JWT) and the signing algorithm (e.g., HMAC SHA256).
- Payload: Contains the claims (statements about an entity, like a user ID or roles).
- Signature: Used to verify the token's authenticity and ensure it hasn't been tampered with. It's created using the header, payload, and a secret key.
AuthN vs. AuthZ in the Gateway
It's crucial to distinguish between Authentication (AuthN) and Authorization (AuthZ):
- Authentication: Verifying the identity of a user or service (e.g., validating a JWT's signature and expiration).
- Authorization: Determining if an authenticated user or service has permission to perform a specific action or access a particular resource (e.g., checking user roles from JWT claims).
The Gateway can handle both, ensuring only valid and authorized requests reach your backend services.
Setting Up Gateway for JWT Security
To integrate JWT security, your Spring Cloud Gateway project typically needs the spring-cloud-starter-gateway and spring-boot-starter-security dependencies.
While spring-boot-starter-security provides a robust security framework, we'll focus on manually handling JWT validation using Gateway filters to illustrate the core concepts.
JWT Validation Flow in Gateway
When a client sends a request with a JWT, the Gateway intercepts it. The typical flow is:
- Extract Token: Get the JWT from the
Authorizationheader. - Validate Token: Verify its signature, check expiration, and ensure it's well-formed.
- Extract Claims: Parse the token to get user details and roles.
- Authorize Request: Based on claims, decide if the request can proceed to the backend service.
Implementing a Custom JWT Filter
We can implement JWT validation using a custom GlobalFilter in Spring Cloud Gateway. This filter will run for all incoming requests before they are routed.
Inside the filter, you'll access the request headers, extract the JWT, and perform your validation logic. If the token is invalid, you can reject the request directly from the Gateway.
Example: Simple JWT Filter
This example demonstrates a basic Spring Cloud Gateway application with a GlobalFilter. It logs the presence of an Authorization: Bearer header, simulating the first step of JWT validation. Run it and try accessing /test with an Authorization header!
package com.example.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import reactor.core.publisher.Mono;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
System.out.println("Gateway started! Try accessing /test with 'Authorization' header.");
}
// Configures a dummy route for the filter to act on
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("test_route", r -> r.path("/test")
.uri("http://httpbin.org:80/get")) // A public echo service
.build();
}
// Our simplified JWT validation filter
@Bean
public GlobalFilter jwtValidationFilter() {
Logger logger = LoggerFactory.getLogger(GatewayApplication.class);
return (exchange, chain) -> {
HttpHeaders headers = exchange.getRequest().getHeaders();
String authHeader = headers.getFirst(HttpHeaders.AUTHORIZATION);
logger.info("Intercepted request to: {}", exchange.getRequest().getURI());
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String jwt = authHeader.substring(7);
logger.info("Found JWT in header: {}", jwt);
// In a real scenario, full JWT validation happens here.
// For this example, we just log it and proceed.
} else {
logger.warn("No 'Authorization: Bearer' header found.");
}
return chain.filter(exchange); // Continue to the next filter/route
};
}
}Securing Routes with Authorization
Once a JWT is validated and its claims (like user roles or scopes) are extracted, you can use these claims for authorization. Spring Cloud Gateway allows you to define authorization rules directly on your routes.
For instance, you could configure a route to only permit requests if the authenticated user has an 'ADMIN' role specified in their JWT payload.
Quick Check: JWT Authorization
After a JWT is validated by the Gateway, which of the following are key benefits of using JWTs for API authentication and authorization in a stateless microservice architecture?
Recap: Secure Gateway with JWTs
You've learned how Spring Cloud Gateway serves as a critical enforcement point for API security. We covered the basics of JWTs—their structure, benefits, and how they enable stateless authentication and authorization.
By implementing custom filters, you can integrate robust JWT validation and leverage claims to secure access to your microservices, ensuring only authorized requests reach your backend.
คำถามที่พบบ่อย
บทเรียน “การยืนยันตัวตนและการอนุญาตด้วย JWT” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การยืนยันตัวตนและการอนุญาตด้วย JWT” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การยืนยันตัวตนและการอนุญาตด้วย JWT”
ใช้งานการยืนยันตัวตนและการอนุญาตด้วย JWT ภายใน Spring Cloud Gateway เพื่อรักษาความปลอดภัยในการเข้าถึง API คุณปฏิบัติ API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การยืนยันตัวตนและการอนุญาตด้วย JWT” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) นี้ได้ไหม
ได้ บทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การยืนยันตัวตนและการอนุญาตด้วย JWT
- การติดตามแบบกระจายด้วย Sleuth และ Zipkin
- การตั้งค่าแบบรวมศูนย์ด้วยเซิร์ฟเวอร์ตั้งค่า
- การเปิดเผยเมตริกด้วย Actuator และ Prometheus