Swagger文档在SpringBoot框架下的配置,Swagger配置登录验证

  1. Swagger文档作为后端接口调用重要的工具之一,下面是文档调用的详细代码
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import io.swagger.annotations.Api;
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.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
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.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.List;

/**
 * Swagger 接口文档配置类
 *
 * @author
 * @date 2023/6/17
 */

@EnableSwaggerBootstrapUI
@EnableSwagger2
@Configuration
public class SwaggerConfig extends WebMvcConfigurationSupport {

    /**
     * 配置扫描的api控制包路径
     * 这里配置的是你后端框架controller类对应的路径
     */
    private static final String BASE_PACKAGE = "xxxxxxxxxxxxxxx.controller";

    /**
     * 服务器路径
     * 代码部署服务的路径,选添,可以不写
     */
    private static final String SERVICE_URL = "xxxxxxxxx";

    /**
     * 配置swagger文档
     *
     * @return docket 对象
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()

                // 设置扫描基础包
                .apis(RequestHandlerSelectors.basePackage(BASE_PACKAGE))

                // 扫描使用Api注解的控制器
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build()

                //添加登录认证
                //这里下面两行代码已经相关下面包可以注释掉,这里是配置的Swagger文档登录验证,需要在application.yml文件中进行相关的配置,配置信息见后面详细情况
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    @Bean
    public RequestMappingInfoHandlerMapping requestMapping() {
        return new RequestMappingHandlerMapping();
    }

    /**
     * 配置 api 文档信息
     *
     * @return 文档信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()

                // 页面标题(自由发挥)
                .title("xxxxx")

                // API描述
                .description("自由发挥")

                // 创建路径
                .termsOfServiceUrl(SERVICE_URL)
                .version("1.0.0")
                .build();
    }

    /**
     * 解决 swagger 静态资源 404问题
     *
     * @param registry 资源路径
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {

        // 解决静态资源无法访问
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");

        // 解决swagger无法访问
        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        // 解决swagger的js文件无法访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        // 解决swagger-bootstrap 无法访问
        registry.addResourceHandler("doc.html").
                addResourceLocations("classpath:/META-INF/resources/");
    }

    private List<ApiKey> securitySchemes() {
        //设置请求头信息
        List<ApiKey> result = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
        result.add(apiKey);
        return result;
    }

    private List<SecurityContext> securityContexts() {
        //设置需要登录认证的路径
        List<SecurityContext> result = new ArrayList<>();

        // 所有请求路径
        result.add(getContextByPath("/.*"));
        return result;
    }

    private SecurityContext getContextByPath(String pathRegex) {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(pathRegex))
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        List<SecurityReference> result = new ArrayList<>();
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        result.add(new SecurityReference("Authorization", authorizationScopes));
        return result;
    }

}

  1. application.yml进行swagger配置信息
## 开启 Swagger的 Basic认证功能,默认是false
swagger:
  # 是否关闭 swagger接口文档访问
  #  production: true
  basic:
    # 开启简单用户验证
    enable: true
    # 用户名(自由发挥)
    username: xx
    # 用户密码(自由发挥)
    password: xx
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring BootSwagger2是现代Web应用程序开发的两个非常有用的工具。这两个工具合在一起可以方便我们快速构建出一个高效、易于维护、易于扩展的Web应用。当我们需要在应用程序中添加安全性认证功能时,基于用户名和密码进行认证就是一种非常常见的方式。Spring Boot提供了各种方式来实现这种认证功能,其中包括使用Spring Security框架来处理身份验证和授权问题。 使用Swagger2的方式也比较简单。我们只需要在应用程序中引入Swagger2组件,然后按照Swagger2提供的API规范编写文档即可。在文档中可以添加注释来指示API支持的认证方式,例如我们可以为带有认证功能的API添加用户名和密码的参数。这样在Swagger UI上就能够方便地测试和调用带有认证功能的API。 在具体实现过程中,我们可以使用Spring Security框架来实现基于用户名和密码的身份认证。Spring Security提供了一个很好的认证框架,可以轻松地实现各种基于用户名和密码的身份认证方案。我们只需要按照文档的要求,将需要保护的API添加到Spring Security的安全配置中,然后在需要保护的API上添加相应的注释即可。在开发过程中我们需要注意一些细节,例如不能将密码明文保存在代码中,需要使用加密的方式来保护用户的密码等等。 总之,Spring BootSwagger2都是非常有用的工具,可以让我们快速构建出高效、易于维护、易于扩展的Web应用程序。在实现基于用户名和密码的身份认证时,我们需要结合使用Spring Security框架来完成。在这个过程中我们需要注意安全性问题,采用加密方式来保护用户的密码等等。这样我们才能够构建出一个高度安全和稳定的Web应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无心 码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值