本文介紹如何在Linux環境下,利用Swagger和spring Security實現基于角色的訪問控制(RBAC),保護Swagger API文檔的安全。
步驟一:集成spring security
Spring Security是強大的安全框架,負責認證和授權。
- 添加依賴: 在pom.xml文件中添加Spring Security依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
- 配置Spring Security: 創建一個配置類(例如SecurityConfig),定義安全規則。以下配置僅允許具有”ADMIN”角色的用戶訪問Swagger ui和API文檔:
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/swagger-ui/**", "/v2/api-docs/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .httpBasic(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
步驟二:配置Swagger
確保Swagger正確配置并與Spring Security集成。
- 添加Swagger依賴: 在pom.xml中添加Swagger依賴:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
- Swagger配置類: 創建一個配置類(例如SwaggerConfig):
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) // 替換成你的包名 .paths(PathSelectors.any()) .build(); } }
步驟三:用戶認證與授權
需要實現用戶認證和授權邏輯。
- 用戶實體: 創建一個User實體類:
@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private String role; // Getters and Setters }
@Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; // 你的UserRepository @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found")); return new User(user.getUsername(), user.getPassword(), getAuthorities(user.getRole())); } private Collection<? extends GrantedAuthority> getAuthorities(String role) { return Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + role)); } }
步驟四:測試
啟動應用,訪問Swagger UI。系統會要求身份驗證。使用正確的用戶名和密碼登錄后,即可訪問Swagger文檔。
此配置確保只有擁有”ADMIN”角色的用戶才能訪問Swagger UI。 請記住將”com.example.demo”替換為你的實際包名,并根據你的數據庫和應用調整用戶存儲和檢索邏輯。 此外,為了更強的安全性,建議使用更高級的安全機制,例如JWT。