在Linux環境下,使用Swagger實現權限控制通常涉及以下幾個步驟:
集成Spring Security:
pom.xml
中添加依賴來實現:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置Spring Security:
WebSecurityConfigurerAdapter
,并重寫相關方法來定義安全規則。@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v2/api-docs/**").authenticated() // 需要認證的URL
.anyRequest().permitAll() // 其他請求允許訪問
.and()
.httpBasic(); // 使用HTTP Basic認證
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password") // {noop}表示不加密密碼
.roles("USER");
}
}
配置Swagger:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
}
訪問Swagger UI:
http://localhost:8080/swagger-ui.html
(假設你的應用程序運行在8080端口)。高級權限控制:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v2/api-docs/**").hasRole("USER") // 需要USER角色
.anyRequest().permitAll()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER")
.and()
.withUser("admin")
.password("{noop}password")
.roles("ADMIN");
}
通過以上步驟,你可以在Linux環境下使用Swagger實現基本的權限控制。根據你的具體需求,可以進一步擴展和定制安全配置。