SpringBoot3集成Oauth2.1——4集成Swagger/OpenAPI3


在我之前的文章中,写了 SpringBoot3集成OpenAPI3(解决Boot2升级Boot3)

访问在线文档页面

当我们同样在SpringBoot3使用oauth2.1也就是我之前的文章中写的。现在我们要处理下面这两个的问题了。

	<!-- 使用springdoc替代springfox集成swagger https://springdoc.org/ -->
		<dependency>
		   	<groupId>org.springdoc</groupId>
		   	<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
		   <version>2.8.6</version>
		</dependency>
		<!-- Knife4j是一个集Swagger2 和 OpenAPI3为一体的增强解决方案 https://doc.xiaominfo.com/ -->
		<dependency>
	    	<groupId>com.github.xiaoymin</groupId>
	    	<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
	    	<version>4.4.0</version>
	    </dependency>

那就是要能访问到我们的openAPI页面,也就是

http://127.0.0.1:18080/doc.html

http://127.0.0.1:18080/swagger-ui/index.html

将我们之前的defaultSecurityFilterChain修改即可。

	@Bean
    @Order(3)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize ->
                authorize
                    .requestMatchers(
                        "/login",                 // 登录页面
                        "/logout",                // 登出端点
                        "/swagger-ui/**",         // Swagger UI
                        "/v3/api-docs/**",        // OpenAPI文档
                        "/webjars/**",            // WebJars资源
                        "/swagger-resources/**",  // Swagger资源
                        "/doc.html"               // Knife4j文档页面
                    ).permitAll()
                    .anyRequest().authenticated()
            )
            .formLogin(Customizer.withDefaults())
            .logout(Customizer.withDefaults());

        return http.build();
    }

此时,就能访问了。
在这里插入图片描述

在这里插入图片描述
当然,访问嘛,肯定401
在这里插入图片描述
以我最常用的knife4j为例。在全局参数的地方,我们是看不到添加认证参数的,只有header和query。
在这里插入图片描述
查看官方:https://doc.xiaominfo.com/docs/action/oauth2-implicit,不难发现,确实有knife4j集成oauth的,不过从代码示例来看,Swagger还是2.x版本,而oauth2也是老版本以前的。所以这个集成就没有参考意义了,里面都是一些在SpringBoot3这个版本里面没有的。

所以我们得出了一个结论,那就是官方目前没有新版本的集成(2025年5月22日)
官方代码中,最后的 提交记录也是4年前。
在这里插入图片描述
看了下代码,其SpringBoot是2.2.x版本

在这里插入图片描述

在这里插入图片描述
所以,只能自己想办法了。折腾了一天,以下是参考的资料和文档(主要原因还是目前很多框架组件,其实对SprignBoot3还不是特别兼容,java8 + boot2是真的钉子户)
https://github.com/xiaoymin/knife4j/issues
https://doc.xiaominfo.com/docs/blog

思路就是,类似postman等接口测试一样,在请求中,添加认证参数
在这里插入图片描述

配置OpenApiConfig

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;

/**
 * @Description: OpenAPI配置
 * @author: 胡涛
 * @mail: hutao_2017@aliyun.com
 * @date: 2025年5月22日12:26:35
 */
@SpringBootConfiguration
public class OpenApiConfig implements WebMvcConfigurer {
	
	@Bean
	public OpenAPI customOpenAPI() {
		return new OpenAPI()
				.info(new Info()
						.title("用户统一平台")
						.version("1.0")
						.description("用户统一管理平台相关接口文档")
						.contact(new Contact()
								.name("Hutao")
								.email("hutao_2017@aliyun.com"))).addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION))
                .components(new Components().addSecuritySchemes(
                        HttpHeaders.AUTHORIZATION,
                        new SecurityScheme()
                                .name(HttpHeaders.AUTHORIZATION)
                                .type(SecurityScheme.Type.HTTP)
                                .scheme("Bearer")
                                .in(SecurityScheme.In.HEADER)
                                .bearerFormat("JWT")
                )
        );
	}
}

这时候,我们将我们从其他地方获取到的token,放入到这里,记得前面添加Bearer
在这里插入图片描述
然而当调用接口,确发现,并没有请求头部参数
在这里插入图片描述
原来需要再访问的接口上面,加上SecurityRequirement

@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)

在这里插入图片描述
这时候就能看到请求头里面的认证参数了。
在这里插入图片描述
此时,就能正常请求了。
在这里插入图片描述
但是吧,这么多接口,咱总不能一个一个的加吧?我们可以实现GlobalOperationCustomizer来添加

import java.util.List;

import org.springdoc.core.customizers.GlobalOperationCustomizer;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class Knife4jOperationCustomizer implements GlobalOperationCustomizer {
    @Override
    public Operation customize(Operation operation, HandlerMethod handlerMethod) {
        List<SecurityRequirement> security = operation.getSecurity();
        if (security == null) {
            security = List.of(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION));
            operation.setSecurity(security);
        }
        return operation;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值