Spring Boot 集成 Swagger 并实现认证保护

引言

随着微服务架构的流行,API 文档的重要性日益凸显。Swagger 是一个非常流行的 API 文档生成工具,它能帮助开发者快速生成 RESTful API 的文档,并且提供了一个友好的界面来测试这些 API。本文将介绍如何在 Spring Boot 项目中集成 Swagger,并实现基于 JWT 的认证保护。

准备工作

  1. Spring Boot 项目: 使用 Spring Initializr 创建一个新的 Spring Boot 项目,确保包含 spring-boot-starter-web 和 spring-boot-starter-security 依赖。
  2. Swagger 依赖: 添加 springfox-boot-starter 依赖。
  3. JWT 相关库: 可以使用 jjwt-api 和 jjwt-impl(以及 jjwt-jackson) 来处理 JWT。

添加依赖

在 pom.xml 文件中添加以下依赖:

复制代码
xml

深色版本

复制代码
1<dependencies>
2    <dependency>
3        <groupId>org.springframework.boot</groupId>
4        <artifactId>spring-boot-starter-web</artifactId>
5    </dependency>
6    <dependency>
7        <groupId>org.springframework.boot</groupId>
8        <artifactId>spring-boot-starter-security</artifactId>
9    </dependency>
10    <dependency>
11        <groupId>io.springfox</groupId>
12        <artifactId>springfox-boot-starter</artifactId>
13        <version>3.0.0</version>
14    </dependency>
15    <dependency>
16        <groupId>io.jsonwebtoken</groupId>
17        <artifactId>jjwt-api</artifactId>
18        <version>0.11.2</version>
19    </dependency>
20    <dependency>
21        <groupId>io.jsonwebtoken</groupId>
22        <artifactId>jjwt-impl</artifactId>
23        <version>0.11.2</version>
24    </dependency>
25    <dependency>
26        <groupId>io.jsonwebtoken</groupId>
27        <artifactId>jjwt-jackson</artifactId>
28        <version>0.11.2</version>
29    </dependency>
30</dependencies>

配置 Swagger

创建一个配置类来配置 Swagger:

复制代码
java

深色版本

复制代码
1import springfox.documentation.builders.PathSelectors;
2import springfox.documentation.builders.RequestHandlerSelectors;
3import springfox.documentation.spi.DocumentationType;
4import springfox.documentation.spring.web.plugins.Docket;
5import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
6
7@Configuration
8@EnableSwagger2WebMvc
9public class SwaggerConfig {
10    @Bean
11    public Docket api() {
12        return new Docket(DocumentationType.SWAGGER_2)
13                .select()
14                .apis(RequestHandlerSelectors.basePackage("com.example"))
15                .paths(PathSelectors.any())
16                .build();
17    }
18}

这里我们指定了 Swagger 应该扫描的包名和路径。

实现 JWT 认证

  1. JWT Token 的生成与验证:创建一个工具类来处理 JWT 的生成和解析。

  2. Security 配置:在 Spring Security 中定义 JWT 认证过滤器和认证管理器。

    java

深色版本

复制代码
1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.context.annotation.Bean;
3import org.springframework.security.authentication.AuthenticationManager;
4import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
5import org.springframework.security.config.annotation.web.builders.HttpSecurity;
6import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
7import org.springframework.security.config.http.SessionCreationPolicy;
8import org.springframework.security.core.userdetails.UserDetailsService;
9import org.springframework.security.crypto.password.PasswordEncoder;
10
11@Configuration
12@EnableWebSecurity
13public class SecurityConfig extends WebSecurityConfigurerAdapter {
14
15    @Autowired
16    private UserDetailsService userDetailsService;
17
18    @Autowired
19    private PasswordEncoder passwordEncoder;
20
21    @Autowired
22    private JwtTokenProvider jwtTokenProvider;
23
24    @Override
25    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
26        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
27    }
28
29    @Override
30    protected void configure(HttpSecurity http) throws Exception {
31        http.cors().and().csrf().disable()
32            .authorizeRequests()
33            .antMatchers("/api/auth/**").permitAll()
34            .anyRequest().authenticated()
35            .and()
36            .addFilterBefore(new JwtAuthenticationTokenFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class)
37            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
38    }
39
40    @Bean
41    @Override
42    public AuthenticationManager authenticationManagerBean() throws Exception {
43        return super.authenticationManagerBean();
44    }
45}

测试 API

启动应用后,可以通过访问 /swagger-ui.html 来查看和测试你的 API 接口。为了测试认证保护的功能,你需要先通过登录接口获取一个 JWT token,然后在 Swagger UI 的 Authorization 字段中输入 Bearer <token> 来进行授权。

结语

以上就是 Spring Boot 项目中集成 Swagger 并实现基于 JWT 的认证保护的步骤。这种方式不仅能够提高 API 的开发效率,还能够保证 API 的安全性。

相关推荐
whinc36 分钟前
Rust技术周刊 2026年第17周
后端·rust
whinc37 分钟前
Rust技术周刊 2026年第18周
后端·rust
xqqxqxxq1 小时前
Java AI智能P图工具技术笔记
java·人工智能·笔记
whinc1 小时前
Rust技术周刊 2026年第16周
后端·rust
谷雨不太卷1 小时前
进程的状态码
java·前端·算法
jieyucx1 小时前
Go语言深度解剖:Map扩容机制全解析(增量扩容+等量扩容+渐进式迁移)
开发语言·后端·golang·map·扩容策略
顾温1 小时前
default——C#/C++
java·c++·c#
空中海1 小时前
02 ArkTS 语言与工程规范
java·前端·spring
楚国的小隐士1 小时前
在AI时代,如何从0接手一个项目?
java·ai·大模型·编程·ai编程·自闭症·自闭症谱系障碍·神经多样性
yaki_ya1 小时前
yaki-C语言:从概念基础到内存解析---数组(array)完全指南
java·c语言·算法