探索 API 文档新境界:Swagger 助力生成带权限控制的 API 文档

news/2025/2/13 5:19:41/

各位开发者朋友们!在咱们的开发工作里,API 文档就像是项目的说明书,清晰准确的文档能让我们的开发效率大幅提升。而当涉及到权限控制时,如何生成既安全又详细的 API 文档就成了一个关键问题。今天,我就和大家好好唠唠如何用 Swagger 来生成带有权限控制的 API 文档。

准备工作:兵马未动,粮草先行

咱们做开发,就像行军打仗,工具和资源就是我们的“粮草”。在使用 Swagger 生成带权限控制的 API 文档之前,得先把相关的依赖添加到项目里。如果你用的是 Maven 项目,在 pom.xml 里加上下面这些依赖:

 
<dependencies><!-- Swagger API 注解 --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><!-- Swagger UI --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><!-- Spring Security --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
</dependencies>

这些依赖就像是我们的武器装备,有了它们,我们才能在开发的战场上“披荆斩棘”。

配置 Swagger:搭建文档生成的舞台

有了依赖,接下来就要对 Swagger 进行配置,让它能按照我们的需求生成 API 文档。创建一个 Swagger 配置类,就像给一场演出搭建舞台一样:

 
java">import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("com.example.controller")).paths(PathSelectors.any()).build();}
}

这里我们指定了要扫描的控制器包路径,这样 Swagger 就能知道从哪里获取 API 的信息了。

权限控制:给文档加上一把安全锁

在实际的项目中,API 文档往往包含了很多敏感信息,所以给文档加上权限控制是非常必要的。我们用 Spring Security 来实现这个功能,创建一个 Spring Security 配置类:

 
java">import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;@Configuration
@EnableWebSecurity
public class SecurityConfig {@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs").hasRole("ADMIN").anyRequest().authenticated().and().httpBasic();return http.build();}@Beanpublic UserDetailsService userDetailsService() {UserDetails user =User.withDefaultPasswordEncoder().username("admin").password("password").roles("ADMIN").build();return new InMemoryUserDetailsManager(user);}
}

在这个配置里,我们规定只有拥有 ADMIN 角色的用户才能访问 Swagger UI 和 API 文档相关的路径,就像给文档加上了一把安全锁,只有有钥匙的人才能打开。

给 API 加上权限注解:让文档清晰明了

在控制器的方法上,我们要添加权限注解和 Swagger 注解,这样在生成的文档里就能清楚地看到每个 API 的权限要求了:

 
java">import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/api")
@Api(value = "示例 API", description = "这是一个带有权限控制的示例 API 文档")
public class ExampleController {@GetMapping("/hello")@ApiOperation(value = "获取问候语", notes = "需要 ADMIN 角色才能访问")@PreAuthorize("hasRole('ADMIN')")public String hello() {return "Hello, World!";}
}

这里用 @PreAuthorize 注解对方法进行权限控制,同时在 @ApiOperation 注解的 notes 属性中说明权限要求,就像给每个 API 贴上了一个“使用说明”。

查看文档:开启探索之旅

当我们完成了以上所有步骤,就可以启动 Spring Boot 应用程序,然后访问 http://localhost:8080/swagger-ui.html(端口号根据实际情况修改)。这时浏览器会弹出 HTTP Basic 认证对话框,输入我们在 SecurityConfig 中配置的用户名和密码(这里是 adminpassword),认证通过后就能看到带有权限信息的 API 文档了,就像打开了一扇通往知识宝库的大门。

注意事项:细节决定成败

在实际项目中,我们要注意一些细节。比如,示例中使用的 withDefaultPasswordEncoder() 并不是很安全,建议使用 BCryptPasswordEncoder 等更安全的密码存储方式。另外,我们可以根据实际业务需求调整权限规则和认证方式,像使用 OAuth2 等。

朋友们,技术的世界就像一片广阔的海洋,我们每一次的探索都是一次成长的机会。通过今天的分享,希望大家能掌握用 Swagger 生成带权限控制的 API 文档的方法,让我们在开发的道路上越走越远,创造出更多优秀的项目!


http://www.ppmy.cn/news/1571620.html

相关文章

React进行路由跳转的方法汇总

在 React 中进行路由跳转有多种方法&#xff0c;具体取决于你使用的路由库和版本。以下是常见的路由跳转方法汇总&#xff0c;主要基于 react-router-dom 库。 1. 使用 useNavigate 钩子&#xff08;适用于 react-router-dom v6&#xff09; useNavigate 是 react-router-dom…

Android图片加载框架Coil,Kotlin

Android图片加载框架Coil&#xff0c;Kotlin implementation("io.coil-kt:coil:1.4.0") import android.os.Bundle import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import coil.Coil i…

2024 Rust现代实用教程:1.1Rust简介与安装更新

文章目录 一、Rust安装二、更新Rust三、Rust的Stable与Nightly版本四、卸载ubuntu安装的cargo和rustup五、rust源设置六、rust交叉编译工具链说明 rustup稳定版交叉编译步骤 步骤 1&#xff1a;安装目标组件步骤 2&#xff1a;安装交叉编译工具链步骤 3&#xff1a;配置环境变…

【设计模式】【行为型模式】模板方法模式(Template Method)

&#x1f44b;hi&#xff0c;我不是一名外包公司的员工&#xff0c;也不会偷吃茶水间的零食&#xff0c;我的梦想是能写高端CRUD &#x1f525; 2025本人正在沉淀中… 博客更新速度 &#x1f4eb; 欢迎V&#xff1a; flzjcsg2&#xff0c;我们共同讨论Java深渊的奥秘 &#x1f…

深入探究 Go 语言中的 Fx 框架:依赖注入的强大工具

在软件开发中&#xff0c;依赖注入&#xff08;Dependency Injection&#xff0c;简称 DI&#xff09;是一种重要的设计模式&#xff0c;它可以帮助我们降低代码的耦合度&#xff0c;提高代码的可测试性和可维护性。Go 语言作为一门高效、简洁的编程语言&#xff0c;拥有许多优…

网络编程(udp tcp)

组播通讯&#xff1a; 发送端实现步骤&#xff1a;创建 UDP 类型的套接字设置组播地址和组播端口向组播地址和组播端口发送数据可以接收回复的数据关闭套接字 2.接收端实现步骤&#xff1a; 1.创建UDP类型的套接字 2.绑定任意IP,组播端口到套接字上 3.加入组播组&#xff08;设…

Lisp语言的软件工程

Lisp语言在软件工程中的应用 引言 在计算机科学的发展历程中&#xff0c;编程语言的演变见证了技术的不断进步与理论的深入探索。Lisp&#xff08;LISt Processing&#xff09;作为一种历史悠久的编程语言&#xff0c;自1958年问世以来&#xff0c;已经走过了超过六十年的风雨…

C# OpenCV机器视觉:颜色量化法提取主色

在热闹繁华的广告设计圈里&#xff0c;阿强是个怀揣无限创意&#xff0c;却总被颜色搭配折腾得焦头烂额的设计师。每次接到项目&#xff0c;面对那些色彩斑斓的素材图片&#xff0c;他就像迷失在彩色迷宫里的小可怜。 “哎呀呀&#xff0c;这么多颜色&#xff0c;到底哪个才是…