springboot oauth2集成swagger2
因为 api 接口访问一般都是保护的,不能直接访问,需要携带 token 才能访问
- 导包
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</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>
<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
- application.properties 配置
# 应用服务 WEB 访问端口
server.port=8085
server.servlet.context-path=/
- 在 application 里面配置 swagger 地址显示
package com.zl.securitytest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author z
*/
@SpringBootApplication
@Slf4j
public class SecurityTestApplication {
public static void main(String[] args) throws UnknownHostException {
ConfigurableApplicationContext applicationContext = SpringApplication.run(SecurityTestApplication.class, args);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = environment.getProperty("server.port");
String path = environment.getProperty("server.servlet.context-path");
path = ("/".equals(path) || path == null ? "" : path);
log.info("\n----------------------------------------------------------\n\t" +
"Application spring-Boot is running! Access URLs:\n\t" +
"Local: \t\thttp://localhost:" + port + path + "/\n\t" +
"External: \thttp://" + ip + ":" + port + path + "/\n\t" +
"Swagger-UI: \t\thttp://" + ip + ":" + port + path + "/doc.html\n" +
"----------------------------------------------------------");
}
}
- swagger 配置
package com.zl.securitytest.config;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
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 z
* @date 2021-12-13 16:42
*/
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
.title("security项目API")
.description("系统化信息化security平台,为您提供最优质的服务")
.version("1.0")
.build())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
// 整合 oauth2
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
return docket;
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeys = new ArrayList<>();
apiKeys.add(new ApiKey("token", "Authorization", "header"));
return apiKeys;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.any()).build());
return securityContexts;
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("all", "access_token");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Bearer", authorizationScopes));
return securityReferences;
}
}
- 编写一个 swagger 接口进行测试
package com.zl.securitytest.controller;
import com.zl.securitytest.common.Result;
import com.zl.securitytest.pojo.SysUser;
import com.zl.securitytest.pojo.UserInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 返回用户信息
*
* @author z
* @date 2021-12-07 15:19
*/
@RestController
@Slf4j
@Api(value = "UserController", tags = "用户信息")
@RequestMapping("/user")
public class UserController {
/**
* 获取用户信息
*
* @return
*/
@ApiOperation(value = "获取用户信息", notes = "获取用户信息")
@GetMapping("/userInfo")
public Result<UserInfoVO> getUser() {
UserInfoVO userInfoVO = new UserInfoVO();
try {
SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
BeanUtils.copyProperties(sysUser, userInfoVO);
userInfoVO.setRoleList(sysUser.getRoleList());
} catch (Exception e) {
log.error("{}", e);
return Result.failed("获取用户信息失败");
}
return Result.ok(userInfoVO);
}
}
启动项目,看到如下界面
进入浏览器进行测试
接口展示
swagger接口测试
- 具体用法实例
controller
/**
* 用户操作 controller
* @author Zhang
*/
@RestController
@RequestMapping("/userAction")
@Api(value = "userActionController", tags = "用户操作")
public class UserActionController {
/**
* 用户操作service
*/
@Resource
private UserActionServiceImpl iUserActionService;
/**
* 查询所有用户
* @return 用户集合
*/
@ApiOperation(value = "查询所有的用户信息", notes = "查询所有的用户信息")
@GetMapping("/getUserList")
public Result<List<User>> getUserList(){
return Result.ok(iUserActionService.getUserList());
}
/**
* 根据用户姓名和性别查询用户信息列表
* @param username 用户姓名
* @param sexCode 用户性别
* @return 用户信息列表
*/
@ApiOperation(value = "根据用户姓名和性别查询用户信息列表", notes = "根据用户姓名和性别查询用户信息列表")
@GetMapping("/getUserInfoByName")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用户姓名", required = true ),
@ApiImplicitParam(name = "sexCode", value = "用户性别", required = true )
})
public Result<List<User>> getUserInfoByName(String username, Int sexCode){
return Result.ok(iUserActionService.getUserInfoByName(username, sexCode));
}
/**
* 新增用户
* @param userVo 添加用户参数接收对象
* @return 新增是否成功
*/
@ApiOperation(value = "新增用户", notes = "新增用户")
@PostMapping("/addUser")
@ApiImplicitParam(name = "userVo", value = "添加用户参数接收对象", required = true )
public Result<String> addUser(@Valid @RequestBody UserVO userVo){
return Result.ok(iUserActionService.addUser(userVo) == 1 ? "新增成功" : "新增失败");
}
/**
* 根据id查询用户信息
* @param id 用户id
* @return 用户信息
*/
@ApiOperation(value = "根据id查询用户信息", notes = "根据id查询用户信息")
@GetMapping("/getUserInfoById")
@ApiImplicitParam(name = "id", value = "用户id", required = true )
public Result<List<User>> getUserInfoById(String id){
return Result.ok(iUserActionService.getUserInfoById(id));
}
/**
* 获取当前学生课程分数全部信息
* @ApiIgnore 表示swagger显示时候忽略的信息
* @param map 参数列表
* @return 课程分数信息
*/
@ApiOperation("获取当前学生课程分数全部信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNum", value = "页数", required = true),
@ApiImplicitParam(name = "pageSize", value = "条数", required = true),
@ApiImplicitParam(name = "classId", value = "班级id", required = true),
@ApiImplicitParam(name = "studentId", value = "学生id", required = true),
})
@GetMapping("/getStuScoreInfoAll")
public R getStuScoreInfoAll(@ApiIgnore @RequestParam Map<String,Object> map){
return R.ok();
}
}
pojo
/**
* 添加用户参数接收vo
* @author Zhang
*/
@Setter
@Getter
@ApiModel(value = "添加用户参数对象")
public class UserVO {
/**
* 用户名称
*/
@NotNull(message = "用户名称不能为空")
@ApiModelProperty(value="用户名称", required = true)
private String username;
/**
* 用户密码
*/
@NotNull(message = "用户密码不能为空")
@ApiModelProperty(value="用户密码", required = true)
private String password;
/**
* 用户性别:0-女 1-男
*/
@NotNull(message = "用户性别不能为空")
@ApiModelProperty(value="用户性别:0-女 1-男", required = true)
private Integer sexCode;
}