淺析如何使用Swagger生成帶權(quán)限控制的API文檔
在咱們的開發(fā)工作里,API 文檔就像是項目的說明書,清晰準確的文檔能讓我們的開發(fā)效率大幅提升。而當涉及到權(quán)限控制時,如何生成既安全又詳細的 API 文檔就成了一個關(guān)鍵問題。今天,我就和大家好好嘮嘮如何用 Swagger 來生成帶有權(quán)限控制的 API 文檔。
準備工作
咱們做開發(fā),就像行軍打仗,工具和資源就是我們的“糧草”。在使用 Swagger 生成帶權(quán)限控制的 API 文檔之前,得先把相關(guān)的依賴添加到項目里。如果你用的是 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>
這些依賴就像是我們的武器裝備,有了它們,我們才能在開發(fā)的戰(zhàn)場上“披荊斬棘”。
配置 Swagger
有了依賴,接下來就要對 Swagger 進行配置,讓它能按照我們的需求生成 API 文檔。創(chuàng)建一個 Swagger 配置類,就像給一場演出搭建舞臺一樣:
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 { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } }
這里我們指定了要掃描的控制器包路徑,這樣 Swagger 就能知道從哪里獲取 API 的信息了。
權(quán)限控制
在實際的項目中,API 文檔往往包含了很多敏感信息,所以給文檔加上權(quán)限控制是非常必要的。我們用 Spring Security 來實現(xiàn)這個功能,創(chuàng)建一個 Spring Security 配置類:
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 { @Bean public 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(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user); } }
在這個配置里,我們規(guī)定只有擁有 ADMIN 角色的用戶才能訪問 Swagger UI 和 API 文檔相關(guān)的路徑,就像給文檔加上了一把安全鎖,只有有鑰匙的人才能打開。
給 API 加上權(quán)限注解
在控制器的方法上,我們要添加權(quán)限注解和 Swagger 注解,這樣在生成的文檔里就能清楚地看到每個 API 的權(quán)限要求了:
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 = "這是一個帶有權(quán)限控制的示例 API 文檔") public class ExampleController { @GetMapping("/hello") @ApiOperation(value = "獲取問候語", notes = "需要 ADMIN 角色才能訪問") @PreAuthorize("hasRole('ADMIN')") public String hello() { return "Hello, World!"; } }
這里用 @PreAuthorize 注解對方法進行權(quán)限控制,同時在 @ApiOperation 注解的 notes 屬性中說明權(quán)限要求,就像給每個 API 貼上了一個“使用說明”。
查看文檔
當我們完成了以上所有步驟,就可以啟動 Spring Boot 應用程序,然后訪問 http://localhost:8080/swagger-ui.html(端口號根據(jù)實際情況修改)。這時瀏覽器會彈出 HTTP Basic 認證對話框,輸入我們在 SecurityConfig 中配置的用戶名和密碼(這里是 admin 和 password),認證通過后就能看到帶有權(quán)限信息的 API 文檔了,就像打開了一扇通往知識寶庫的大門。
注意事項
在實際項目中,我們要注意一些細節(jié)。比如,示例中使用的 withDefaultPasswordEncoder() 并不是很安全,建議使用 BCryptPasswordEncoder 等更安全的密碼存儲方式。另外,我們可以根據(jù)實際業(yè)務(wù)需求調(diào)整權(quán)限規(guī)則和認證方式,像使用 OAuth2 等。
到此這篇關(guān)于淺析如何使用Swagger生成帶權(quán)限控制的API文檔的文章就介紹到這了,更多相關(guān)Swagger生成API文檔內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java 文創(chuàng)商城系統(tǒng)的實現(xiàn)流程
讀萬卷書不如行萬里路,只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+mysql+maven+tomcat實現(xiàn)一個文創(chuàng)商城系統(tǒng),大家可以在過程中查缺補漏,提升水平2021-11-11SpringSecurity 手機號登錄功能實現(xiàn)
這篇文章主要介紹了SpringSecurity 手機號登錄功能實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友一起看看吧2023-12-12SpringBoot實現(xiàn)郵件發(fā)送的示例代碼
電子郵件是—種用電子手段提供信息交換的通信方式,是互聯(lián)網(wǎng)應用最廣的服務(wù)。本文詳細為大家介紹了SpringBoot實現(xiàn)發(fā)送電子郵件功能的示例代碼,需要的可以參考一下2022-04-04Java實現(xiàn)圖片翻轉(zhuǎn)以及任意角度旋轉(zhuǎn)
這篇文章主要為大家詳細介紹了Java實現(xiàn)圖片翻轉(zhuǎn)以及任意角度旋轉(zhuǎn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-01-01Mybatis中SqlSession下的四大對象之執(zhí)行器(executor)
mybatis中sqlsession下的四大對象是指:executor, statementHandler,parameterHandler,resultHandler對象。這篇文章主要介紹了Mybatis中SqlSession下的四大對象之執(zhí)行器(executor),需要的朋友可以參考下2019-04-04RestTemplate發(fā)送get和post請求,下載文件的實例
這篇文章主要介紹了RestTemplate發(fā)送get和post請求,下載文件的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09