前提:原项目,有springsecurity,且使用jwt
1.依赖
<!--版本号-->
<springdoc.version>1.6.6</springdoc.version>
<!--springdoc-->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${springdoc.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-security</artifactId>
<version>${springdoc.version}</version>
</dependency>
2. 配置文件
正在使用的配置:(有一些好像确实没啥用)
springdoc:
api-docs:
enabled: true
packagesToScan: com.mods.browser.controller
swagger-ui:
disable-swagger-default-url: off #禁用swagger-ui默认的petstore网址 默认就是swagger-ui.html
csrf:
enabled: true #启用CSRF支持
enabled: true #开启swagger-ui
供参考的配置
#swagger配置
springdoc:
version: '1.0.4'
packagesToScan: com.xxxx.account.controller #包扫描路径
swagger-ui:
path: /swagger-ui.html #swagger-ui访问路径 http://ip:端口/swagger-ui.html
csrf:
enabled: true #启用CSRF支持
enabled: true #开启swagger-ui
display-request-duration: true # 展示请求所耗时间ms
operations-sorter: method #api排序方式 alpha 字母 method http方法
groups-order: desc # 排序顺序
disable-swagger-default-url: true #禁用swagger-ui默认的petstore网址 默认就是swagger-ui.html
model-and-view-allowed: true #运行modelAndView展示(返回页面)
show-actuator: true #加了spring-boot-actuator依赖的可开启
group-configs:
- group: account
paths-to-match: /accountTbl/**
- group: users
packages-to-scan: com.xxxx.user.controller
3. springdoc配置类
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@Configuration
public class Swagger3Config {
@Bean
public OpenAPI springShopOpenAPI() {
//信息
Info info = new Info()
.title("swagger3 测试-标题")
.description("这是一段描述:springboot-swagger3")
.version("v1.0.0");
//鉴权组件(随便起名的)
SecurityScheme securityScheme = new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")//固定写法
.bearerFormat("JWT")
.in(SecurityScheme.In.HEADER)
.name("Authorization");
Components components = new Components()
.addSecuritySchemes("bearer-jwt", securityScheme);
//鉴权限制要求(随便起名的)
SecurityRequirement securityRequirement = new SecurityRequirement()
.addList("bearer-jwt", Arrays.asList("read", "write"));
return new OpenAPI()
.info(info)
.components(components)
.addSecurityItem(securityRequirement);
}
}
4. springsecurity配置类
- 主要是最下边的放行路径,配置类使用的其他类暂不提供,可私信
import com.mods.auth.component.JwtAuthenticationTokenFilter;
import com.mods.auth.component.RestAuthenticationEntryPoint;
import com.mods.auth.component.RestfulAccessDeniedHandler;
import com.mods.auth.costum.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtProperties jwtProperties;
@Autowired
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
return new RestfulAccessDeniedHandler();
}
@Bean
public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
return new RestAuthenticationEntryPoint();
}
@Autowired
public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//通过配置实现,不需要JWT令牌就可以访问的接口,在配置文件里写,一般写接口
for (String uri : jwtProperties.getPermitAllURI()) {
http.authorizeRequests().antMatchers(uri).permitAll();
}
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
// .antMatchers("/**").permitAll() //放行全部
// .anyRequest().authenticated()//任何没匹配上antMatchers的,只需要用户被验证有token的
.anyRequest().access("@rbacService.hasPermission(request,authentication)")//可以放行经过验证有权限的用户
.and()
.cors()
.and()
.exceptionHandling()
.accessDeniedHandler(restfulAccessDeniedHandler())//没有权限时自定义异常
.authenticationEntryPoint(restAuthenticationEntryPoint());//没有token时自定义异常
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
@Override
public void configure(WebSecurity web) {
//配置跳过security验证拦截的路径,配置的放行路径
web.ignoring().antMatchers(
"/swagger-ui/index.html",
"/swagger-ui.html",
"/swagger-ui/**",
"/v3/api-docs/**",
"/v3/api-docs"
);
}
}
5.参考用,springfox -> springdoc
Swagger2注解 | OpenAPI3(swagger3)注解 |
---|---|
@ApiParam | @Parameter |
@ApiOperation | @Operation |
@Api | @Tag |
@ApiImplicitParams | @Parameters |
@ApiImplicitParam | @Parameter |
@ApiIgnore | @Parameter(hidden = true) or @Operation(hidden = true) or @Hidden |
@ApiModel | @Schema |
@ApiModelProperty | @Schema |