OAuth2 与 JWT 基础
掌握 OAuth2 授权的核心概念,以及 JSON Web Token(JWT)安全交换信息的方式。
OAuth2 与 JWT 基础 是 CoddyKit 上的免费 Spring Boot 4 Microservices & REST APIs 课时。 这是第 1 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Microservices & REST APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Microservices & REST APIs 课程共包含 3 节课。
本课时的部分内容尚未翻译,以英文显示。
Why API Security Matters
When building applications, especially those with REST APIs, security is paramount. You're exposing data and functionality that needs protection.
Without proper security, your API could be vulnerable to unauthorized access, data breaches, or malicious attacks. This lesson lays the groundwork for understanding how to secure your services.
AuthN vs. AuthZ: Key Differences
Before diving in, let's clarify two critical terms:
- Authentication (AuthN): Verifying who a user or client is. Think of it as showing your ID to prove your identity.
- Authorization (AuthZ): Determining what an authenticated user or client is allowed to do. This is like a bouncer checking your ticket to see if you can enter a specific area.
OAuth2 primarily focuses on authorization.
Meet OAuth2: The Authorization Standard
OAuth2 (Open Authorization 2.0) is an industry-standard protocol for authorization. It allows a third-party application (the 'client') to obtain limited access to an HTTP service (the 'resource server') on behalf of a user (the 'resource owner').
Crucially, OAuth2 enables this access without the user having to share their credentials (username and password) directly with the client application.
Roles in OAuth2
OAuth2 defines four main roles that interact in the authorization process:
- Resource Owner: The user who owns the protected resources.
- Client: The application requesting access to the resource owner's protected resources.
- Authorization Server: The server that authenticates the resource owner and issues access tokens to the client.
- Resource Server: The server hosting the protected resources, capable of accepting and responding to protected resource requests using access tokens.
How OAuth2 Grants Access
OAuth2 uses different 'grant types' (also known as flows) to issue an access token. An access token is a credential that grants the client access to specific resources on the resource server.
The choice of grant type depends on the client's type (e.g., web application, mobile app, server-side application) and its security requirements. The Authorization Code Flow is widely used for traditional web applications.
Introducing JWTs: Secure Information
A JSON Web Token (JWT), pronounced 'jot', is a compact, URL-safe means of representing claims to be transferred between two parties. These claims are pieces of information about an entity (typically, the user) and additional metadata.
JWTs are often used as the format for access tokens in OAuth2, providing a self-contained way to securely transmit information about the user and their permissions.
Anatomy of a JWT
A JWT consists of three parts, separated by dots (.):
- Header: Contains metadata about the token itself, like the type of token (JWT) and the signing algorithm used (e.g., HMAC SHA256 or RSA).
- Payload: Contains the 'claims' – statements about an entity (like a user) and additional data. Claims can be registered (standardized), public, or private.
- Signature: Used to verify that the sender of the JWT is who it says it is and that the message hasn't been tampered with. It's created using the header, the payload, and a secret key.
JWT Structure: A Closer Look
Here's what a typical JWT might look like. Each part is Base64Url encoded:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c- The first part is the Header.
- The second part is the Payload.
- The third part is the Signature.
These parts are encoded separately and joined by dots.
Decoding JWT Parts (Concept)
The header and payload of a JWT are simply Base64Url encoded JSON. This means anyone can easily decode them to read their contents. The security comes from the signature, which verifies the token's integrity and authenticity.
Try decoding a sample Base64Url string in Java:
import java.util.Base64;
public class Main {
public static void main(String[] args) {
String encodedHeader = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
String encodedPayload = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ";
System.out.println("Decoded Header:");
decodeAndPrint(encodedHeader);
System.out.println("\nDecoded Payload:");
decodeAndPrint(encodedPayload);
}
private static void decodeAndPrint(String encodedString) {
try {
byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedString);
String decodedString = new String(decodedBytes, "UTF-8");
System.out.println(decodedString);
} catch (Exception e) {
System.out.println("Error decoding: " + e.getMessage());
}
}
}Why Use JWTs?
JWTs offer several advantages, especially in distributed systems like microservices:
- Statelessness: The server doesn't need to store session information. Each JWT contains all necessary user data.
- Scalability: Since tokens are self-contained, any service can validate them without a central session store, simplifying scaling.
- Compact & URL-Safe: They are small and can be easily transmitted in URL parameters, POST requests, or HTTP headers.
- Self-Contained: They contain all the information about the user, reducing the need for database lookups on every request.
Check Your Understanding
Which of the following statements best describes the primary purpose of OAuth2?
Lesson Summary
In this lesson, you've gained a foundational understanding of API security principles. We distinguished between Authentication (who you are) and Authorization (what you can do).
You learned about OAuth2 as a standard for secure authorization, allowing controlled access to resources. We also explored JSON Web Tokens (JWTs), understanding their structure and benefits as a compact, self-contained way to transmit information, often used as access tokens within OAuth2.
常见问题解答
「OAuth2 与 JWT 基础」课时是免费的吗?
是的 — 「OAuth2 与 JWT 基础」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Microservices & REST APIs 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Microservices & REST APIs 课程共包含 3 节课。
「OAuth2 与 JWT 基础」这节课中我会学到什么?
掌握 OAuth2 授权的核心概念,以及 JSON Web Token(JWT)安全交换信息的方式。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Microservices & REST APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Spring Boot 4 Microservices & REST APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Spring Boot 4 Microservices & REST APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 3 节。
「OAuth2 与 JWT 基础」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Spring Boot 4 Microservices & REST APIs 课中编写并运行代码吗?
能。每节 Spring Boot 4 Microservices & REST APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- OAuth2 与 JWT 基础
- 保护 REST 端点
- 基于角色的访问控制