SpringBoot+Security+Swagger2配置

SpringBoot+Security+Swagger2配置

前言:本来想用Swagger3呢,但是找了好久都没有找到Swagger3的文档,百度也搜不到。这里说的是添加security的登录、登出配置。所以就借用了网上的部分代码做的

  1. 首先在pom.xml中添加swagger2的坐标
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
    <!--移除swagger-models 1.5.20 依赖,存在Swagger2异常:Illegal DefaultValue null for parameter type integer问题-->
    <exclusions>
        <exclusion>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
        </exclusion>
        <exclusion>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.5.21</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-models</artifactId>
    <version>1.5.21</version>
</dependency>
  1. 创建一个swagger的配置文件
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.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * Swagger2Config 配置文件
 */
@Configuration
public class Swagger2Config implements WebMvcConfigurer {
    /**
     * 导入配置文件中的值
     */
    @Value("${debugger_tools}")
    private Boolean debuggerTools;
    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制那些借口暴露给Swagger来展现
     * 本例采用指定扫描的包路径来定义指定要建立API的目录
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
        		// 这里表示是否启用swagger
                .enable(debuggerTools)
                // 项目前缀
                .apiInfo(new ApiInfoBuilder()
                        .title("*******")//网页标题
                        .description("一个简单的测试")//网页描述
                        .contact(new Contact("tom",null,"tom@163.com"))//用户名,url,email
                        .version("1.00")//接口版本号
                        .build());
    }

}
  1. 在security中configure配置,其他配置这里不介绍
/**
 * 拦截请求后的权限设置
 *
 * @param http
 * @throws Exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            // 设置Swagger2匿名访问
            .antMatchers("/swagger-ui.html", "/webjars/**",
                    "/v2/**", "/swagger-resources/**").permitAll()
}
  1. 实现以上两步,即可通过http://IP:端口/项目前缀/swagger-ui.html访问swagger,项目前缀有则写没有则不写;例如http://localhost:8080/swagger-ui.html
  2. 细心的朋友会发现:因为Security是自带登录、登出请求的,因此swagger并不会生成这两个请求,因此需要手动去增加这两个请求。也就是这里swagger3中我尚未找到解决办法。在swagger3中这里使用的方法很多都弃用了,也没找到官方文档去解决这个问题。说再多都是废话,最终实现才是目的,因此使用Swagger2,上代码:
import com.fasterxml.classmate.TypeResolver;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.OperationBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiDescription;
import springfox.documentation.service.Operation;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.ApiListingScannerPlugin;
import springfox.documentation.spi.service.contexts.DocumentationContext;
import springfox.documentation.spring.web.readers.operation.CachingOperationNameGenerator;

import java.util.*;

/**
 * 手动添加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) {
        return Arrays.asList(login(),unLogin());
    }
    /**
     * 定义用户名的字段
     * @return
     */
    public Parameter username(){
        return new ParameterBuilder()
                .description("用户名")
                .type(new TypeResolver().resolve(String.class))
                .name("username")
                .parameterType("form")
                .parameterAccess("access")
                .defaultValue("admin")
                .required(true)
                .modelRef(new ModelRef("string"))
                .build();
    }

    /**
     * 定义密码的字段
     * @return
     */
    public Parameter password(){
        return new ParameterBuilder()
                .description("密码")
                .type(new TypeResolver().resolve(String.class))
                .name("password")
                .parameterType("form")
                .parameterAccess("access")
                .defaultValue("admin123")
                .required(true)
                .modelRef(new ModelRef("string"))
                .build();
    }
    /**
     * 定义验证码的字段
     */
    public Parameter code(){
        return new ParameterBuilder()
                .description("验证码")
                .type(new TypeResolver().resolve(String.class))
                .name("code")
                .parameterType("form")
                .parameterAccess("access")
                .required(false)
                .modelRef(new ModelRef("string"))
                .build();
    }
    /**
     * 定义返回消息
     * @return
     */
    public Set<ResponseMessage> responseMessages(){
        Set<ResponseMessage> messages = new HashSet<>();
        messages.add(new ResponseMessageBuilder().code(200).message("ok").build());
        messages.add(new ResponseMessageBuilder().code(401).message("Unauthorized").build());
        messages.add(new ResponseMessageBuilder().code(403).message("Forbidden").build());
        messages.add(new ResponseMessageBuilder().code(404).message("Not Found").build());
        return messages;
    }

    /**
     * 登录请求
     * @return
     */
    public ApiDescription login(){
        Operation loginOperation = new OperationBuilder(new CachingOperationNameGenerator())
                .tags(Collections.singleton("用户接口"))
                .summary("登录")
                .notes("登录")
                .method(HttpMethod.POST)
                .consumes(Collections.singleton(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) // 接收参数格式
                .produces(Collections.singleton(MediaType.APPLICATION_JSON_VALUE)) // 返回参数格式
                .parameters(Arrays.asList(username(),password(),code())) //定义参数
                .responseMessages(responseMessages())
                .build();

        ApiDescription loginApiDescription = new ApiDescription("login", "/login","登录接口",
                Arrays.asList(loginOperation), false);
        return loginApiDescription;
    }
    /**
     * 退出登录请求
     * @return
     */
    public ApiDescription unLogin(){
        Operation unLoginOperation = new OperationBuilder(new CachingOperationNameGenerator())
                .tags(Collections.singleton("用户接口"))
                .summary("登出")
                .notes("登出")
                .method(HttpMethod.GET)
                .produces(Collections.singleton(MediaType.APPLICATION_JSON_VALUE)) // 返回参数格式
                .responseMessages(responseMessages())
                .build();
        ApiDescription unLoginApiDescription = new ApiDescription("logout", "/logout","退出登录接口",
                Arrays.asList(unLoginOperation), false);
        return unLoginApiDescription;
    }
    /**
     * 是否使用此插件
     *
     * @param documentationType swagger文档类型
     * @return true 启用
     */
    @Override
    public boolean supports(DocumentationType documentationType) {
        return DocumentationType.SWAGGER_2.equals(documentationType);
    }
}
  1. 在第二步中有一个属性是debuggerTools,说是导入配置文件中的值,是的,正式中swagger是为了方便调试用的,所以在生产环境中是无需启用,因此可以使用配置文件来控制是否启用swagger。可以在不同的环境变量中定义debugger_tools属性值。根据启用不同环境配置,来决定是否启用swagger(SpringBoot如何配置多环境)
    如下:
# 是否启用swagger,postman调试
# application-dev.yml环境
debugger_tools: true


# application-test.yml、application-prod.yml环境
debugger_tools: false
  1. 结果,因为我的登录、登出路径是重定义加了/user 。默认没有
    在这里插入图片描述

参考文章:
Security如何配置swagger2
swagger2添加Security登录接口

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot是一个用于创建独立的、基于生产级别的Spring应用程序的框架。它简化了Spring应用程序的配置和部署过程,并提供了一套强大的开发工具和约定,使开发人员能够更专注于业务逻辑的实现。 MyBatis Plus是MyBatis的增强工具,它提供了一系列的便利功能和增强特性,使得使用MyBatis更加简单和高效。它包括了代码生成器、分页插件、逻辑删除、乐观锁等功能,可以大大提高开发效率。 Redis是一个开源的内存数据库,它支持多种数据结构,如字符串、哈希、列表、集合、有序集合等。Redis具有高性能、高可用性和可扩展性的特点,常用于缓存、消息队列、分布式锁等场景。 Driver是指数据库驱动程序,它是用于连接数据库和执行SQL语句的软件组件。在Spring Boot中,我们可以通过配置数据源和引入相应的数据库驱动程序来实现与数据库的交互。 Knife4j是一款基于Swagger的API文档生成工具,它提供了更加美观和易用的界面,可以方便地查看和测试API接口。 Swagger是一套用于设计、构建、文档化和使用RESTful风格的Web服务的工具。它可以自动生成API文档,并提供了交互式的界面,方便开发人员进行接口测试和调试。 JWT(JSON Web Token)是一种用于身份验证和授权的开放标准。它通过在用户和服务器之间传递加密的JSON对象来实现身份验证和授权功能,避免了传统的基于Session的身份验证方式带来的一些问题。 Spring Security是Spring提供的一个安全框架,它可以集成到Spring Boot应用程序中,提供身份验证、授权、攻击防护等安全功能。通过配置Spring Security,我们可以实现对API接口的访问控制和权限管理。 关于Spring Boot + MyBatis Plus + Redis + Driver + Knife4j + Swagger + JWT + Spring Security的Demo,你可以参考以下步骤: 1. 创建一个Spring Boot项目,并引入相应的依赖,包括Spring Boot、MyBatis Plus、Redis、数据库驱动程序等。 2. 配置数据源和数据库驱动程序,以及MyBatis Plus的相关配置,如Mapper扫描路径、分页插件等。 3. 集成Redis,配置Redis连接信息,并使用RedisTemplate或者Jedis等工具类进行操作。 4. 集成Knife4j和Swagger配置Swagger相关信息,并编写API接口文档。 5. 集成JWT和Spring Security配置安全相关的信息,如登录认证、权限管理等。 6. 编写Controller层的代码,实现具体的业务逻辑。 7. 运行项目,通过Swagger界面进行接口测试。 希望以上内容对你有帮助!如果还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

£漫步 云端彡

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

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

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

打赏作者

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

抵扣说明:

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

余额充值