springboot springsecurity使用springdoc,从springfox迁移到springdoc,swagger2改swagger3

本文档介绍了如何在SpringBoot项目中整合SpringDoc和SpringSecurity,实现JWT认证的API文档和安全配置。首先,展示了所需的依赖和配置文件,包括启用API文档、设置包扫描、配置CSRF支持等。接着,详细讲解了SpringDoc的OpenAPI配置类,用于定义API的基本信息和安全策略。最后,提供了SpringSecurity配置类,包括鉴权、放行路径设置以及JWT令牌的处理。文章还提及了从Springfox迁移到SpringDoc的相关注解对照。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前提:原项目,有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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值