swagger文档页面添加token请求头

使用swagger-ui的过程中,swagger页面调用的时候会统一在header里面加入输入token参数的位置

1. 在pom中加入依赖

 <properties>
        <maven.compile.source>1.8</maven.compile.source>
        <maven.compile.target>1.8</maven.compile.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <swagger.version>2.7.0</swagger.version>
    </properties>
        <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
        </dependency>
        </dependency>

2.编写API配置类放置在Application类的同级或子包下


import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import zut.edu.ding.utils.JwtTokenUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@EnableOpenApi
@Configuration
public class Swagger2Config {
    /**
     * Every Docket bean is picked up by the swagger-mvc framework - allowing for multiple
     * swagger groups i.e. same code base multiple swagger resource listings.
     */
    @Bean
    public Docket customDocket(){
         RequestParameterBuilder builder = new RequestParameterBuilder();
        RequestParameter parameter = builder.name(HttpConstant.AUTHORIZATION).description("token").required(false).in("header").build();
        List<RequestParameter> parameterList = new ArrayList<>(2);
        parameterList.add(parameter);

        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .build()
                .globalOperationParameters(parameterList)
                .apiInfo(apiInfo());
    }

    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("demo")
                //创建人
                .contact(new Contact("demo", "", ""))
                //版本号
                .version("1.0")
                //描述
                .description("demo REST API")
                .build();
    }
}

在权限框架下使用

如果你项目配置了Spring Security、shiro、自定义权限框架的话swagger-ui是会被拦截到的,需要配置放行。

 

效果:可以看到所有的api都有一个输入Authorization的地方

 

 

更好的方案

虽然上面这种方式能解决问题,但是不好的地方是每次请求都要输入请求头,很麻烦,下面给出一种更简便的方式

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
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.List;

import static com.google.common.collect.Lists.newArrayList;

/**
 * @author lism
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).
                useDefaultResponseMessages(false)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("^(?!auth).*$"))
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }
    private List<SecurityScheme> securitySchemes(){
        return Collections.singletonList(new ApiKey(HttpConstant.AUTHORIZATION, HttpConstant.AUTHORIZATION, "header"));
    }

    private List<SecurityContext> securityContexts() {
        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .operationSelector(null)
                        .build()
        );
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        return Collections.singletonList(new SecurityReference("Authorization", new AuthorizationScope[]{authorizationScope}));
    }
}

效果:配置完之后点击右上角的Authorize,弹出认证窗口之后输入请求token,这样之后的每次请求的请求头都会带有token认证信息

Swagger2 可以通过添加全局请求参数的方式来自动添加 Authorization 请求头。具体步骤如下: 1. 创建一个拦截器类,用于在请求头添加 Authorization 参数。 ```java public class AuthInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = "your_token_here"; request.addHeader("Authorization", token); return true; } // 省略其他方法 } ``` 2. 在 Swagger2 配置类中添加全局请求参数。 ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Autowired private AuthInterceptor authInterceptor; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()) .globalOperationParameters(Collections.singletonList(new ParameterBuilder() .name("Authorization") .description("Authorization token") .modelRef(new ModelRef("string")) .parameterType("header") .required(true) .build())) .securityContexts(Collections.singletonList(SecurityContext.builder() .securityReferences(Collections.singletonList(SecurityReference.builder() .reference("Authorization") .scopes(new AuthorizationScope[0]) .build())) .build())) .securitySchemes(Collections.singletonList(new ApiKey("Authorization", "Authorization", "header"))); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API") .description("API documentation") .version("1.0") .build(); } // 添加拦截器 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authInterceptor); } } ``` 在这里我们使用 `globalOperationParameters` 方法添加一个全局请求参数,该参数名为 `Authorization`,类型为 `header`,并且是必须的。我们还需要使用 `securityContexts` 和 `securitySchemes` 方法来配置 Swagger2 使用该参数作为授权信息。 当我们访问 Swagger2 文档时,会自动向请求头添加 Authorization 参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值