Swagger在Linux系统中的权限管理实践
一、总体思路
二、分层权限控制方案
三、Java Spring Boot集成示例
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-ui.html","/webjars/**","/swagger-resources/**","/v2/api-docs").authenticated()
.anyRequest().permitAll()
.and().formLogin().loginPage("/login").permitAll()
.and().logout().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
@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();
}
}
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/secured")
@PreAuthorize("hasRole('USER')")
public String securedEndpoint() {
return "Secured";
}
}
四、Node.js Express集成示例
// openapi spec片段
{
"openapi": "3.0.0",
"info": { "title": "My API", "version": "1.0.0" },
"components": {
"securitySchemes": {
"Bearer": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT" }
}
},
"security": [{ "Bearer": [] }]
}
五、生产环境加固清单