SpringBoot+Cloud+oauth2.0+JWT集成swagger及swagger-bootstrap-ui详细步骤

实现效果图

先看是否效果图是否符合你的预期符合预期你在接着往下看
在这里插入图片描述

引入Maven依赖

 <!-- swagger文档API 关于swagger-ui.html的依赖我去掉了-->
 		//这个是优化界面的类似插件会让doc.html变得更好看
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>
        //swagger2的依赖 
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        //swagger-ui的界面 这个访问doc.html
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
        

swagger的配置文件属性



import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
/**
 * @author hanfeng
 * @date 2021/8/24
 */
@Configuration
@EnableSwagger2
@EnableAutoConfiguration
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
@EnableSwaggerBootstrapUI
public class SwaggerAutoConfiguration
{
   
   
    /**
     * 默认的排除路径,排除Spring Boot默认的错误处理路径和端点
     */
    private static final List<String> DEFAULT_EXCLUDE_PATH = Arrays.asList("/error", "/actuator/**");

    private static final String BASE_PATH = "/**";

    @Bean
    @ConditionalOnMissingBean
    public SwaggerProperties swaggerProperties()
    {
   
   
        return new SwaggerProperties();
    }

    @Bean
    public Docket api(SwaggerProperties swaggerProperties)
    {
   
   
        // base-path处理
        if (swaggerProperties.getBasePath().isEmpty())
        {
   
   
            swaggerProperties.getBasePath().add</
<think>好的,我现在需要帮助用户解决在Swagger UI中配置Auth认证的问题。用户提到了Swagger3 UI的安全认证设置,所以首先我得确认Swagger3和之前版本的差异。根据之前的引用内容,比如引用[1]提到Swagger UI支持多种授权机制,比如Basic Auth、Bearer TokenOAuth等。可能用户需要的是如何在Swagger3中启用这些认证方式。 接下来,我需要回忆Swagger的基本配置步骤。通常,在使用Spring Boot集成Swagger时,需要创建一个配置类,使用@Configuration和@EnableSwagger2或@EnableSwagger3注解。不过Swagger3对应的注解可能不同,比如@EnableOpenApi?或者可能还是沿用之前的名称,这点需要确认。比如引用[4]中提到了使用swagger-bootstrap-ui的依赖,可能用户的项目中已经集成Swagger UI,但需要配置安全认证。 然后,根据引用[3]中的代码片段,有一个Authorize方法,使用[FromBody]来获取BasicAuthCredentials,这可能涉及到在Swagger UI中如何发送认证信息。所以,配置SecuritySchemes和SecurityContext是关键。需要指导用户如何通过Docket的securitySchemes和securityContext方法来添加认证方式。 另外,用户可能遇到跨域问题,引用[2]提到了跨域配置,这可能和认证配置无关,但需要注意是否会影响接口测试时的请求发送。不过用户的问题主要集中在Auth认证,所以先聚焦于此。 可能还需要考虑不同的认证类型,比如OAuth2和API Key的设置方法。比如Bearer Token可能需要设置一个头部参数Authorization,携带Bearer令牌。在Swagger配置中,需要定义对应的SecurityScheme类型为HTTP,scheme为bearer,bearerFormat为JWT等。 最后,需要验证配置是否生效,访问Swagger UI界面后是否出现了Authorize按钮,输入凭证后请求是否携带正确的认证信息。可能还需要提到测试时的注意事项,比如确保后端接口正确处理认证信息。 总结步骤应该是:添加依赖、创建配置类、定义SecurityScheme、配置SecurityContext、启动应用并测试。同时,需要根据不同的认证类型调整SecurityScheme的参数,比如Basic Auth使用HTTP基本认证,OAuth2则需要更详细的配置,比如tokenUrl、flow类型等。 另外,用户提到的swagger3ui可能指的是Springfox Swagger3还是SpringDoc,因为Springfox已经停止更新,可能用户使用的是SpringDoc,这需要确认。不过根据引用[4]中的依赖是swagger-bootstrap-ui,可能还是基于Springfox的。所以需要按照Springfox的配置方式来写。 可能还需要注意版本兼容性问题,比如Swagger3的配置是否和Swagger2有所不同,比如注解或配置类的方法是否有变化。需要确保示例代码的准确性,避免用户因为版本问题无法正确配置。 最后,生成相关问题需要考虑用户可能进一步的需求,比如如何自定义UI界面(如引用[4]提到的)、如何处理跨域问题(引用[2])、如何测试带认证的API等。</think>在Swagger UI中配置Auth认证主要涉及定义安全策略与关联作用范围。以下是基于Swagger3的详细配置步骤: ### 一、添加Swagger3依赖 若使用Spring Boot,需在`pom.xml`中添加: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` ### 二、配置Security Scheme 创建Swagger配置类,定义认证类型: ```java import springfox.documentation.service.*; import springfox.documentation.spi.service.contexts.SecurityContext; @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .securitySchemes(Arrays.asList( new HttpSecurityScheme("BasicAuth", SecuritySchemeType.HTTP) .scheme("basic"), new HttpSecurityScheme("BearerToken", SecuritySchemeType.HTTP) .scheme("bearer") .bearerFormat("JWT") )) .securityContexts(Arrays.asList( SecurityContext.builder() .securityReferences(Arrays.asList( new SecurityReference("BasicAuth", new AuthorizationScope[0]), new SecurityReference("BearerToken", new AuthorizationScope[0]) )) .operationSelector(o -> true) // 应用到所有接口 .build() )); } } ``` ### 三、接口层标注作用域 在Controller方法上指定需要的认证类型: ```java @PostMapping("/auth-test") @Operation(security = { @SecurityRequirement(name = "BearerToken") }) public ResponseEntity<?> authTest() { return ResponseEntity.ok("认证通过"); } ``` ### 四、访问与测试 1. 启动应用后访问`http://localhost:8080/swagger-ui/` 2. 点击右上角**Authorize**按钮 3. 输入对应凭证: - **BasicAuth**: 格式为`username:password`的Base64编码 - **BearerToken**: 直接输入JWT令牌 >[!NOTE] > 若使用OAuth2,需额外配置`clientId`、`authorizationUrl`等参数[^1] ### 五、验证请求头 成功配置后,发送请求时会自动携带如`Authorization: Bearer eyJhbGciOi...`的头部[^3]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值