OAuth 2.0 与 JWT 授权在 Java 中的入门介绍
现代 Web 应用和 API 需要可靠的认证与授权机制。在 Java 开发领域,OAuth 2.0 和 JWT(JSON Web 令牌)已成为事实上的标准。OAuth 2.0 提供了一种委托访问的协议,而 JWT 则是一种紧凑且自包含的数据传输格式。在本文中,我们将探讨如何使用 Spring Security 和流行库在 Java 中结合这些技术。
您将学习如何配置授权服务器、生成和验证 JWT 令牌,以及保护您的 REST 端点。本材料将对希望深入掌握安全知识的新手和经验丰富的 Java 开发者均有所帮助。
OAuth 2.0 基础:流程与角色
OAuth 2.0 定义了四种角色:资源所有者、客户端(应用)、授权服务器 和 资源服务器。最流行的流程(授权类型)包括:
- 授权码 — 用于具有服务器端组件的 Web 应用。
- 客户端凭证 — 用于服务器到服务器的通信。
- 资源所有者密码 — 用于受信任的客户端(已弃用)。
- 隐式 — 用于单页应用(不再推荐)。
在 Java 中,我们可以使用 spring-security-oauth2-authorization-server 实现 OAuth 2.0 服务器。让我们看一个配置基本授权服务器的示例。
在 Spring Boot 上设置授权服务器
将依赖添加到 pom.xml:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-authorization-server</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>创建配置类 SecurityConfig.java:
@Configuration@EnableWebSecuritypublic class SecurityConfig {
@Bean @Order(1) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); return http.build(); }
@Bean @Order(2) public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated()) .formLogin(Customizer.withDefaults()); return http.build(); }
@Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient registeredClient = RegisteredClient.withId("client-id") .clientId("my-client") .clientSecret("{noop}secret") .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUri("http://localhost:8080/login/oauth2/code/my-client") .scope("read") .scope("write") .build(); return new InMemoryRegisteredClientRepository(registeredClient); }}JWT:令牌结构与生成
JWT 由三部分组成:头部、载荷 和 签名。头部包含令牌类型和加密算法。载荷包含声明,例如 sub(主体)、exp(过期时间)和 roles。签名确保数据完整性。
为了在 Java 中处理 JWT,我们使用 io.jsonwebtoken:jjwt 库。添加依赖项: