Swagger2进阶:集成统一认证和SpringSecurity的登录接口

4,133 阅读4分钟

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

SpringBoot集成Swagger之后,在Controller层添加相应的注解,即可生成接口文档,在前后端的项目中广泛使用。

统一认证

在具体的项目中,大部分资源都是被保护的(参考:Spring Boot优雅的集成Spring Security),那怎么在Swagger页面设置全局的登录Token呢?Swagger提供了SecurityScheme抽象类,来专门解决认证的问题,其下有3个实现,分别是:

  • ApiKey:支持header和query两种认证方式;
  • BasicAuth:简单认证;
  • OAuth:基于OAuth2的认证方式。

今天咱们主要说下ApiKey的header认证,就是将Swagger页面上,所有请求的header中,添加登录凭证Token。

集成spring4all社区提供的starter

<!-- swagger2 -->
<dependency>
  <groupId>com.spring4all</groupId>
  <artifactId>swagger-spring-boot-starter</artifactId>
  <version>1.9.1.RELEASE</version>
</dependency>

在配置文件中配置:

# swagger配置
swagger:
  # 是否开启swagger
  enabled: true
  title: Gits_接口文档
  # 全局统一鉴权配置
  authorization:
    key-name: GitsSessionID

这样在请求头中就会添加key为GitsSessionID的token了,启动项目,访问ip:port/swagger-ui.html

image
点击左下角Authorize按钮,设置token,就可以愉快的使用swagger了
image

添加SpringSecurity登录接口到Swagger页面

有些场景我们需要手动将接口添加到Swagger中,比如:非SpringMVC注解暴露接口(如定义在filter中),无法通过这种注解方式生成api接口文档。

SpringSecurity的用户名密码登录接口,就是在filter中进行了拦截,可以回顾之前的一篇文章:Spring Security密码登录源码分析(附流程图)

因此在Swagger中看不到该登录接口,这样在平时的开发测试中,非常不方便,我们需要先在postman工具中,访问登录接口获取Token,再回到Swagger页面设置Token,作为一个钢铁直男,我就想只在Swagger页面中完成这种操作,应该怎么办呢?

通过实现swagger提供的插件ApiListingScannerPlugin,可以手动将接口添加到swagger文档里。

下面咱们尝试将SpringSecurity登录接口添加到swagger中:

/**
 * 手动添加swagger接口,如登录接口等
 *
 * @author songyinyin
 * @date 2020/6/17 下午 10:03
 */
@Component
public class SwaggerAddtion implements ApiListingScannerPlugin {
    /**
     * Implement this method to manually add ApiDescriptions
     * 实现此方法可手动添加ApiDescriptions
     *
     * @param context - Documentation context that can be used infer documentation context
     * @return List of {@link ApiDescription}
     * @see ApiDescription
     */
    @Override
    public List<ApiDescription> apply(DocumentationContext context) {
        Operation usernamePasswordOperation = new OperationBuilder(new CachingOperationNameGenerator())
            .method(HttpMethod.POST)
            .summary("用户名密码登录")
            .notes("username/password登录")
            .consumes(Sets.newHashSet(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) // 接收参数格式
            .produces(Sets.newHashSet(MediaType.APPLICATION_JSON_VALUE)) // 返回参数格式
            .tags(Sets.newHashSet("登录"))
            .parameters(Arrays.asList(
                new ParameterBuilder()
                    .description("用户名")
                    .type(new TypeResolver().resolve(String.class))
                    .name("username")
                    .defaultValue("admin")
                    .parameterType("query")
                    .parameterAccess("access")
                    .required(true)
                    .modelRef(new ModelRef("string"))
                    .build(),
                new ParameterBuilder()
                    .description("密码")
                    .type(new TypeResolver().resolve(String.class))
                    .name("password")
                    .defaultValue("123456")
                    .parameterType("query")
                    .parameterAccess("access")
                    .required(true)
                    .modelRef(new ModelRef("string"))
                    .build(),
                new ParameterBuilder()
                    .description("验证码唯一标识")
                    .type(new TypeResolver().resolve(String.class))
                    .name("randomKey")
                    .defaultValue("666666")
                    .parameterType("query")
                    .parameterAccess("access")
                    .required(true)
                    .modelRef(new ModelRef("string"))
                    .build(),
                new ParameterBuilder()
                    .description("验证码")
                    .type(new TypeResolver().resolve(String.class))
                    .name("code")
                    .parameterType("query")
                    .parameterAccess("access")
                    .required(true)
                    .modelRef(new ModelRef("string"))
                    .build()
            ))
            .responseMessages(Collections.singleton(
                new ResponseMessageBuilder().code(200).message("请求成功")
                    .responseModel(new ModelRef(
                        "xyz.gits.boot.common.core.response.RestResponse")
                    ).build()))
            .build();

        ApiDescription loginApiDescription = new ApiDescription("login", "/login", "登录接口",
            Arrays.asList(usernamePasswordOperation), false);

        return Arrays.asList(loginApiDescription);
    }

    /**
     * 是否使用此插件
     * 
     * @param documentationType swagger文档类型
     * @return true 启用
     */
    @Override
    public boolean supports(DocumentationType documentationType) {
        return DocumentationType.SWAGGER_2.equals(documentationType);
    }
}

代码有点长,稍微解释一下。supports方法为是否使用此插件,apply方法可以手动添加ApiDescription,其返回值是ApiDescription集合,通过建造者模式可以构造ApiDescription。先构造一个用户名密码登录的Operation,其中指定了请求方式(method)、标签(tags)、参数(parameters)、返回结果(responseMessages)等。最后用构建好的usernamePasswordOperation、请求路径、请求说明等,构造成ApiDescription进行返回。

这样就能在swagger页面上看到刚刚定义的接口了。

image
这样就做到了登录-认证-访问被保护资源,三步都在swagger中操作,美滋滋。

成果展示

  1. 获取验证码

image

  1. 登录获取token

image

  1. swagger统一认证

image

  1. 访问被保护的资源

image
本节完成了Swagger统一认证,并集成Security登录接口,极大的方便了平时的开发测试。


好汉且慢,原创不易,点个赞再走呗。关注公众号可以白嫖😘,别下次一定了,就这次🤣