swagger2-身份认证Authenticatio(一)BasicAuth

这里使用spring boot 2.1.8

一、引入maven依赖

        
            io.springfox
            springfox-swagger2
            2.9.2
        
        
            io.springfox
            springfox-swagger-ui
            2.9.2
        

        
            com.github.xiaoymin
            swagger-bootstrap-ui
            1.9.6
        

二、配置类

@Configuration
@EnableSwagger2
//@EnableSwaggerBootstrapUI
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
//                .pathMapping("/")
                .select()
                // 指定当前包路径,这里就添加了两个包,注意方法变成了basePackage,中间加上成员变量splitor
                .apis(RequestHandlerSelectors.basePackage("com.example.lwp.swagger2.swagger2authdemo.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                ;
        return docket;
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot整合Swagger")
                .description("SpringBoot整合Swagger,详细信息......")
                .version("9.0")
                .contact(new Contact("张三", "blog.csdn.net", "[email protected]"))
                .contact(new Contact("李四", "blog.csdn.net", "[email protected]"))
//                        .license("The Apache License")
//                        .licenseUrl("http://www.baidu.com")
                .build();
    }

    /**
     * SecurityScheme 子类 BasicAuth OAuth ApiKey
     * @return
     */
    private List securitySchemes(){
        List list = new ArrayList<>();
        // basicAuth SwaggerBootstrapUI支持的不好,使用swagger原生UI
        list.add(new BasicAuth("basicAuth"));
        return list;
    }
}

三、controller

authorizations = {@Authorization(value=“basicAuth”)}

@RestController
@RequestMapping("/auth")
@Api(tags = {"auth模块"}, description = "需要鉴权的模块(描述)") //
public class AuthController {

    @GetMapping("/hello")
    @ApiOperation("hello入口")
    public String hello(String username){
        return "hello " + username;
    }

    @GetMapping("/hello1")
    @ApiOperation(value = "auth hello1接口", authorizations = {@Authorization(value="basicAuth")})
    public String hello1(String username){
        return "hello1 " + username;
    }
    ...

四、swagger-ui

1.swagger-ui中显示有锁标志
在这里插入图片描述
2. 点击Authrize按钮
在这里插入图片描述
3.弹出验证表单,将内容填写,这里用户名密码使用 admin/123
swagger2-身份认证Authenticatio(一)BasicAuth_第1张图片
4.输入成功关闭
swagger2-身份认证Authenticatio(一)BasicAuth_第2张图片
5.查看对应接口显示已经使用basicAuth
在这里插入图片描述
6.测试接口,报文中显示

curl -X GET "http://localhost:8080/auth/hello1?username=13" -H "accept: */*" -H "authorization: Basic YWRtaW46MTIz"

swagger2-身份认证Authenticatio(一)BasicAuth_第3张图片

你可能感兴趣的:(swagger2,auth)