本文介绍如何在Linux环境下,利用Swagger和Spring Security实现基于角色的访问控制(RBAC),保护Swagger API文档的安全。
步骤一:集成Spring Security
Spring Security是强大的安全框架,负责认证和授权。
pom.xml文件中添加Spring Security依赖:org.springframework.boot spring-boot-starter-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集成。
pom.xml中添加Swagger依赖:io.springfox springfox-swagger22.9.2 io.springfox springfox-swagger-ui2.9.2
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
}
UserDetailsService接口:@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
privat
e 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。