pom.xml
<dependency>
<groupId>com.github.xiaoymingroupId>
<artifactId>knife4j-spring-boot-starterartifactId>
<version>3.0.3version>
<exclusions>
<exclusion>
<groupId>com.google.guavagroupId>
<artifactId>guavaartifactId>
exclusion>
<exclusion>
<groupId>io.swaggergroupId>
<artifactId>swagger-modelsartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>com.google.guavagroupId>
<artifactId>guavaartifactId>
<version>31.1-jreversion>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>${springfox.version}version>
<exclusions>
<exclusion>
<groupId>io.swaggergroupId>
<artifactId>swagger-modelsartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>io.swaggergroupId>
<artifactId>swagger-modelsartifactId>
<version>1.5.21version>
<scope>compilescope>
dependency>
SpringConfig.java - 配置类
package work.linruchang.lrcutilsweb.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import work.linruchang.lrcutilsweb.config.handlerInterceptor.ApiDocHandlerInterceptor;
import work.linruchang.lrcutilsweb.util.convert.BeanConvertFactory;
import javax.annotation.PostConstruct;
/**
* @author LinRuChang
* @version 1.0
* @date 2022/09/20
* @since 1.8
**/
@Configuration
public class SpringConfig implements WebMvcConfigurer {
@Value("${sys.swagger.author-name}")
private String authorName;
@Value("${sys.swagger.author-url}")
private String authorUrl;
@Value("${sys.swagger.author-email}")
private String authorEmail;
@Value("${sys.name}")
private String sysName;
@Autowired
ApiDocHandlerInterceptor apiDocHandlerInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(apiDocHandlerInterceptor)
.addPathPatterns("/doc.html","/swagger-ui/","/swagger-ui.html");
}
/**
*
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/swagger-ui.html", "/swagger-ui/");
registry.addRedirectViewController("/swagger-ui.html/", "/swagger-ui/");
}
@Bean
public Docket customDocketBean() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(true)
.apiInfo(new ApiInfoBuilder()
.description("个人在线工具类网站后台接口API")
.termsOfServiceUrl("https://doc.xiaominfo.com/")
.contact(new Contact(authorName,authorUrl,authorEmail))
.version("1.0")
.build())
.groupName("lrc-utils-web-api")
.select()
.apis(RequestHandlerSelectors.basePackage("work.linruchang.lrcutilsweb.controller"))
.paths(PathSelectors.any())
.build();
}
}
ApiDocHandlerInterceptor.java - Api文档账号密码校验拦截器 - 使用Basic认证
package work.linruchang.lrcutilsweb.config.handlerInterceptor;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import work.linruchang.lrcutilsweb.service.SysDictService;
import work.linruchang.lrcutilsweb.util.EnhanceSpringUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* Api拦截器
*
* @author LinRuChang
* @version 1.0
* @date 2022/11/28
* @since 1.8
**/
@Component
@Slf4j
public class ApiDocHandlerInterceptor implements HandlerInterceptor {
@Autowired
SysDictService sysDictService;
/**
* 进入方法前
* @param request current HTTP request
* @param response current HTTP response
* @param handler chosen handler to execute, for type and/or instance evaluation
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean authStatusFlag = false;
String authorization = EnhanceSpringUtil.getCurrentRequestHeader("Authorization");
log.info("Api接口文档认证信息【Authorization】:{}", authorization);
String authType = null;
String authInfoCredentials = null;
String userName = null;
List<String> authorizationInfos = StrUtil.splitTrim(authorization, StrUtil.SPACE);
if(CollUtil.size(authorizationInfos) == 2) {
authType = authorizationInfos.get(0);
authInfoCredentials = authorizationInfos.get(1);
if (StrUtil.isNotBlank(authInfoCredentials)) {
if (StrUtil.equalsAnyIgnoreCase(authType, "BASIC")) {
String authInfo = Base64.decodeStr(authInfoCredentials);
List<String> authInfos = StrUtil.splitTrim(authInfo, StrUtil.COLON);
userName = CollUtil.size(authInfos) >= 2 ? authInfos.get(0) : null;
String password = CollUtil.size(authInfos) >= 2 ? authInfos.get(1) : null;
//这里自行获取数据库中的用户、密码信息进行校验是否正确
Dict dbUserInfo = getApiSwaggerUserInfo(userName);
if(dbUserInfo != null && StrUtil.equals(password,dbUserInfo.getStr("password"))) {
authStatusFlag = true;
}
}
}
}
//认证失败
if (!authStatusFlag) {
response.setHeader("WWW-Authenticate", StrUtil.format("{} realm=\"请填写正确的Api文档管理员账号、密码信息\"", StrUtil.blankToDefault(authType,"BASIC")));
response.setStatus(401);
return false;
}
//认证成功
return true;
}
public Dict getApiSwaggerUserInfo(String loginName) {
Dict swaggerConfig = sysDictService.getSwaggerConfig();
if(StrUtil.equals(loginName,swaggerConfig.getStr("loginName"))) {
return swaggerConfig;
}
return null;
}
}
//注意:
无退出登录,如果需要退出,自行删除浏览器缓存,或者直接使用谷歌插件【清除历史记录,缓存和Cookie Chrome】进行删除缓存即可