spring-boot swagger2 设置全局token,解决接口需要token验证的问题

1、Swagger2 配置类

关键是在securitySchemes()方法配置里增加需要token的配置。
配置完成后,swagger-ui.html里右上角会有一个Authorize的按钮,录入该token即能成功调用相关接口

@Configuration
@EnableSwagger2
public class SwaggerConfig {
	@Bean
	public Docket swaggerSpringMvcPlugin() {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
				.apis(RequestHandlerSelectors.withClassAnnotation(Api.class)).paths(PathSelectors.any()).build()
				.securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
	}
	private List securitySchemes() {
        List apiKeyList= new ArrayList();
        apiKeyList.add(new ApiKey("token", "token", "header"));
        return apiKeyList;
    }
 
    private List securityContexts() {
        List securityContexts=new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }
 
    List defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List securityReferences=new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

	// 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				// 页面标题1
				.title("易电云平台RESTful API")
				// 描述
				.description("易电云平台").termsOfServiceUrl("http://localhost:8080/")
				// 创建人
				.contact(new Contact("Presoft", "http://www.presoft.com.cn", ""))
				// 版本号
				.version("1.0.1").build();
	}
}

2、访问拦截配置

注意要 implements  WebMvcConfigurer 接口,extends   WebMvcConfigurationSupport 不好使

@Configuration
public class InterceptorConfig  implements WebMvcConfigurer {
	@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/fileUpdataApi/upload","/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
    }
	
}

 

3、红框内添加token,保存之后,每次访问header中都会带全局token

spring-boot swagger2 设置全局token,解决接口需要token验证的问题_第1张图片

 原文

https://www.jianshu.com/p/07a6d2ac9fed

https://www.jianshu.com/p/7a24d202b395

https://blog.csdn.net/pengdandezhi/article/details/81182701

 

你可能感兴趣的:(swagger,token,Java)