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 的安全性。

相关推荐
砍材农夫37 分钟前
物联网实战|Spring Boot MQTT平台 |emqx broker实战
spring boot·spring·spring cloud·mybatis
似璟如你1 小时前
Java 开发者的 Go 语法基础:从 0 开始快速上手 Go
java·开发语言·后端·golang·go·编程语言
zzz_23681 小时前
TencentDB-Agent-Memory 深度解析:让多个 Agent 共享项目经验的记忆中枢
java·开发语言·jvm·人工智能·agent·memory·tencent db
vx-程序开发2 小时前
django医院预约挂号系统---附源码23353
java·javascript·spring boot·python·eclipse·django·php
金斗潼关2 小时前
ysoserial的使用
java
ruleslol2 小时前
volatile 关键字
java
Codelinghu2 小时前
AI 写代码越强,程序员越不能只懂代码
后端
卡卡敲码2 小时前
Skills 撞车了,Agent 怎么选
后端
羑悻2 小时前
周一早上三件事砸过来,我以为要延期,结果 AI 替我扛了一半!
后端
文艺理科生2 小时前
3 年,8 种方案,1 次重构:LangChain 记忆方案如何从混乱走向清晰
前端·后端·架构