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