微信登录

OAuth2 集成 - 资源服务器 - 保护资源服务器

Java - Web - Spring 《OAuth2 集成 - 资源服务器 - 保护资源服务器》

一、引言

在当今的分布式系统中,OAuth2 已经成为了一种广泛使用的授权框架,用于保护资源服务器上的资源。资源服务器是存储和管理受保护资源的地方,如用户信息、文件等。本文将详细介绍如何在 Spring 项目中集成 OAuth2 来保护资源服务器,并提供具体的演示代码。

二、OAuth2 基本概念

在深入学习如何保护资源服务器之前,我们先来了解一下 OAuth2 的几个重要概念:
| 概念 | 描述 |
| —— | —— |
| 资源所有者(Resource Owner) | 通常是用户,拥有受保护的资源,并可以授予第三方应用访问这些资源的权限。 |
| 客户端(Client) | 代表资源所有者请求访问受保护资源的第三方应用。 |
| 授权服务器(Authorization Server) | 负责验证资源所有者的身份,并向客户端颁发访问令牌(Access Token)。 |
| 资源服务器(Resource Server) | 存储受保护资源的服务器,使用访问令牌来验证客户端的请求是否合法。 |

三、搭建 Spring Boot 资源服务器项目

1. 创建项目

首先,我们使用 Spring Initializr 创建一个新的 Spring Boot 项目,添加以下依赖:

  1. <dependencies>
  2. <!-- Spring Web -->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-web</artifactId>
  6. </dependency>
  7. <!-- Spring Security OAuth2 Resource Server -->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
  11. </dependency>
  12. </dependencies>

2. 配置资源服务器

application.properties 中添加以下配置,指定授权服务器的信息:

  1. spring.security.oauth2.resourceserver.jwt.issuer-uri=https://your-auth-server.com

这里的 issuer-uri 是授权服务器的发行者 URI,资源服务器将使用该 URI 来验证访问令牌的合法性。

3. 配置 Spring Security

创建一个配置类来配置 Spring Security,保护我们的资源:

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  4. import org.springframework.security.web.SecurityFilterChain;
  5. @Configuration
  6. public class SecurityConfig {
  7. @Bean
  8. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  9. http
  10. .authorizeRequests()
  11. .anyRequest().authenticated()
  12. .and()
  13. .oauth2ResourceServer()
  14. .jwt();
  15. return http.build();
  16. }
  17. }

上述代码配置了所有请求都需要进行身份验证,并使用 JWT(JSON Web Token)来验证访问令牌。

4. 创建受保护的资源端点

创建一个简单的控制器来提供受保护的资源:

  1. import org.springframework.web.bind.annotation.GetMapping;
  2. import org.springframework.web.bind.annotation.RestController;
  3. @RestController
  4. public class ResourceController {
  5. @GetMapping("/protected")
  6. public String protectedResource() {
  7. return "This is a protected resource.";
  8. }
  9. }

四、测试资源服务器

1. 获取访问令牌

首先,你需要从授权服务器获取一个有效的访问令牌。这通常涉及到用户登录和授权的过程,具体实现取决于授权服务器的配置。

2. 发送请求

使用获取到的访问令牌,向资源服务器发送请求:

  1. curl -H "Authorization: Bearer <your-access-token>" http://localhost:8080/protected

如果访问令牌有效,你将看到以下响应:

  1. This is a protected resource.

如果访问令牌无效或过期,你将收到一个 401 Unauthorized 响应。

五、总结

通过以上步骤,我们成功地在 Spring Boot 项目中集成了 OAuth2 来保护资源服务器。主要步骤包括:

  1. 创建 Spring Boot 项目并添加必要的依赖。
  2. 配置资源服务器,指定授权服务器的信息。
  3. 配置 Spring Security,使用 JWT 验证访问令牌。
  4. 创建受保护的资源端点。
  5. 测试资源服务器,确保只有持有有效访问令牌的客户端才能访问受保护的资源。

通过 OAuth2 的集成,我们可以有效地保护资源服务器上的资源,提高系统的安全性。希望本文能帮助你更好地理解和应用 OAuth2 来保护资源服务器。