接口文档神器---Swagger权限控制

Swagger权限控制

  • Swagger2登录安全控制
  • Swagger2 BasicAuth身份认证
  • Swagger2 ApiKey身份认证

Swagger2登录安全控制

  • 需要在appliction.properties中添加如下语句:
swagger.basic.enable=true
swagger.basic.username=username
swagger.basic.password=123456
swagger.production=false
swagger2.enabled=true
  • 在swagger类中开启如下注解:
@Configuration
@EnableSwagger2
@Configuration
@EnableSwagger2
//@EnableSwaggerBootstrapUI
@Profile({"dev", "test", "pre", "prod"})
public class Swagger2UiConfiguration extends WebMvcConfigurerAdapter  {

    @Value("${swagger2.enable}")
    private boolean swagger2Enable;

	@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2)
                .enable(swagger2Enable)
                // 绑定swagger-ui的展示内容
				.apiInfo(apiInfo())
				.select()
                // 绑定扫描的类
				.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
				.build()
				.enable(swagger2Enable)
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
	}


    /**
     * 指定swagger2 ui的显示格式
     * @return
     */
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
                .title("swagger和springBoot整合演示")
                .description("swagger的API文档演示效果")
				.version("1.0")
                .build();
	}

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

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


	private List<SecurityScheme> securitySchemes() {
		List<SecurityScheme> list = new ArrayList<>();
		list.add(new BasicAuth("basicAuth"));
		list.add(new ApiKey("write_token","write_token","header"));
		list.add(new ApiKey("read_token","read_token","query"));

		return list;
	}

	private List<SecurityContext> securityContexts() {
		return Arrays.asList(SecurityContext.builder()
				.securityReferences(defaultAuth())
				.forPaths(PathSelectors.any())
				.build()
		);
	}

}

  • 展示效果
    在这里插入图片描述

Swagger2 BasicAuth身份认证

在这里插入图片描述
在这里插入图片描述

Swagger2 ApiKey身份认证

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

实例演示

package com.example.springbootswagger2.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


import com.example.springbootswagger2.model.Student;



@Api(value = "Swagger2RestController",
        description = "学生服务")
@RestController
public class Swagger2RestController {

    /**
     * 组合所有的学生信息
     */
	List<Student> students = new ArrayList<Student>();
	{
		students.add(new Student("Sajal", "IV", "India"));
		students.add(new Student("Lokesh", "V", "India"));
		students.add(new Student("Kajal", "III", "USA"));
		students.add(new Student("Sukesh", "VI", "USA"));
	}

    /**
     *
     * @return
     */
    @ApiOperation(value = "以列表形式返回学生信息",
			responseContainer="List",
			response = Student.class,
            tags = "getStudents",
            authorizations={@Authorization(value="basicAuth")})
    @ApiResponses(value = {
			@ApiResponse(code = 200, message = "Suceess|OK"),
			@ApiResponse(code = 401, message = "not authorized!"),
			@ApiResponse(code = 403, message = "forbidden!!!"),
			@ApiResponse(code = 404, message = "not found!!!") })
	@RequestMapping(value = "/getStudents", method = RequestMethod.GET)
	public List<Student> getStudents() {
		return students;
	}


    /**
     *
     * @param name
     * @return
     */
	@ApiOperation(value = "获取指定名字的学生",
            response = Student.class,
            tags = "getStudentByName",
            authorizations={@Authorization(value="read_token")})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Suceess|OK"),
            @ApiResponse(code = 401, message = "not authorized!"),
            @ApiResponse(code = 403, message = "forbidden!!!"),
            @ApiResponse(code = 404, message = "not found!!!") })
	@RequestMapping(value = "/getStudent/{studentName}", method = RequestMethod.GET)
	public Student getStudentByName(@RequestParam @ApiParam(value = "studentName") String name) {
		return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0);
	}


    /**
     *
     * @param country
     * @return
     */
	@ApiOperation(value = "获取指定国家的学生",
            responseContainer="List",
            response = Student.class,
            tags = "getStudentByCountry",
            authorizations={@Authorization(value="read_token")})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Suceess|OK"),
            @ApiResponse(code = 401, message = "not authorized!"),
            @ApiResponse(code = 403, message = "forbidden!!!"),
            @ApiResponse(code = 404, message = "not found!!!") })
	@RequestMapping(value = "/getStudentByCountry/{country}", method = RequestMethod.GET)
	public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) {
		System.out.println("Searching Student in country : " + country);
		List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country))
				.collect(Collectors.toList());
		System.out.println(studentsByCountry);
		return studentsByCountry;
	}


    /**
     *
     * @param cls
     * @return
     */
	@ApiOperation(value = "获取指定班级的学生",
            responseContainer="List",
            response = Student.class,
            tags="getStudentByClass",
            authorizations={@Authorization(value="read_token")})
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "Suceess|OK"),
			@ApiResponse(code = 401, message = "not authorized!"),
			@ApiResponse(code = 403, message = "forbidden!!!"),
			@ApiResponse(code = 404, message = "not found!!!") })
	@RequestMapping(value = "/getStudentByClass/{cls}", method = RequestMethod.GET)
	public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) {
		return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList());
	}


    @ApiOperation(value = "添加学生",
            tags="addStudent", 
            authorizations={@Authorization(value="write_token")})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Suceess|OK"),
            @ApiResponse(code = 401, message = "not authorized!"),
            @ApiResponse(code = 403, message = "forbidden!!!"),
            @ApiResponse(code = 404, message = "not found!!!") })
    @RequestMapping(value = "/addStudent", method = RequestMethod.POST, consumes = {"application/json"}, produces = {"application/json"})
    public Boolean addStudent(@ApiParam(value = "student") @RequestBody Student student) {
        return students.add(student);
    }

    @ApiOperation(value = "添加学生V2",
            tags="addStudentV2", 
            authorizations={@Authorization(value="write_token")})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", paramType = "query"),
            @ApiImplicitParam(name = "cls", value = "班级", paramType = "query"),
            @ApiImplicitParam(name = "country", value = "国家", paramType = "query")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Suceess|OK"),
            @ApiResponse(code = 401, message = "not authorized!"),
            @ApiResponse(code = 403, message = "forbidden!!!"),
            @ApiResponse(code = 404, message = "not found!!!") })
    @RequestMapping(value = "/addStudentV2", method = RequestMethod.GET)
    public Boolean addStudentV2(@RequestParam String name,
                                @RequestParam String cls,
                                @RequestParam String country) {
	    Student student = new Student(name, cls, country);
        return students.add(student);
    }

    @ApiOperation(value = "查找指定班级指定名字的学生", tags = "getStudentByNameAndCls",
            authorizations={@Authorization(value="read_token")})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Suceess|OK"),
            @ApiResponse(code = 401, message = "not authorized!"),
            @ApiResponse(code = 403, message = "forbidden!!!"),
            @ApiResponse(code = 404, message = "not found!!!") })
    @RequestMapping(value = "getStudentByNameAndCls", method = RequestMethod.GET)
    public Student getStudentByNameAndCls(@RequestParam String name, @RequestParam String cls) {
	    return students.stream()
                .filter(x -> x.getCls().equals(cls) && x.getName().equalsIgnoreCase(name))
                .collect(Collectors.toList()).get(0);
    }

    @ApiOperation(value = "删除指定名字的学生", tags = "delStudentByName",
            authorizations={@Authorization(value="basicAuth")})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Suceess|OK"),
            @ApiResponse(code = 401, message = "not authorized!"),
            @ApiResponse(code = 403, message = "forbidden!!!"),
            @ApiResponse(code = 404, message = "not found!!!") })
    @RequestMapping(value = "delStudentByName", method = RequestMethod.GET)
    public Student delStudentByName(@RequestParam String name) {
	    Student tempStudent = null;
        for (Student student : students) {
            if (student.getName().equalsIgnoreCase(name)) {
                tempStudent = student;
                break;
            }
        }

        students.remove(tempStudent);

        return tempStudent;
    }
}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swagger Maven Plugin是一个用于生成Swagger接口文档的Maven插件。它可以帮助开发人员在构建项目时自动生成Swagger规范的JSON或YAML文件,以便于API文档的管理和使用。 使用Swagger Maven Plugin生成接口文档swagger.json或swagger.yaml的步骤如下: 1. 在项目的pom.xml文件中添加Swagger Maven Plugin的依赖配置: ```xml <build> <plugins> <plugin> <groupId>com.github.kongchen</groupId> <artifactId>swagger-maven-plugin</artifactId> <version>3.1.8</version> <configuration> <!-- 配置Swagger文档的基本信息 --> <apiSources> <apiSource> <springmvc>true</springmvc> <locations>com.example.controller</locations> <basePath>/api</basePath> <info> <title>API文档</title> <version>1.0.0</version> <description>API接口文档</description> <termsOfServiceUrl>http://example.com/terms-of-service</termsOfServiceUrl> <contact> <email>[email protected]</email> </contact> <license> <name>Apache 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.html</url> </license> </info> </apiSource> </apiSources> </configuration> <executions> <execution> <phase>compile</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ``` 2. 在项目根目录下执行以下命令生成Swagger接口文档: ``` mvn compile swagger:generate ``` 3. 执行完上述命令后,Swagger Maven Plugin会根据配置的信息扫描项目中的接口,并生成Swagger规范的JSON或YAML文件。生成的文件默认保存在项目的target目录下的swagger目录中。 生成的Swagger接口文档可以通过访问http://localhost:8080/api/swagger-ui.html(假设项目部署在本地的8080端口)来查看和测试API接口。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值