在前后端交互时,某些接口需要指定权限才能访问,虽然可以在@ApiOperation
注解的notes参数上自己加上,但是每个接口都要手动写,有点儿。。。
基于此需求,我们可以使用swagger提供的OperationBuilderPlugin
,通过扫描权限注解自动扩展接口的描述信息
项目使用到哪个权限框架,就用哪个配置就行,能直接使用
文档参数分组可参考之前的组件封装:swagger2文档基于knife4j 2.0.5二次封装工具
组件提供了诸如yaml配置分组等一些功能,可自行查看更新日志使用
1 Spring Security 注解展示
将Spring Security的PostAuthorize
、PostFilter
、PreAuthorize
、PreFilter
的注解信息追加到接口描述中.
import com.google.common.base.Optional;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.stereotype.Component;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1001)
public class SecurityOperationBuilderPlugin implements OperationBuilderPlugin {
@Override
public void apply(OperationContext context) {
String notes = context.operationBuilder().build().getNotes();
StringBuilder notesBuilder = new StringBuilder(notes == null ? "" : notes);
getClassAnnotationNote(notesBuilder, context);
getMethodAnnotationNote(notesBuilder, context);
context.operationBuilder().notes(notesBuilder.toString());
}
@Override
public boolean supports(DocumentationType delimiter) {
return true;
}
private void getClassAnnotationNote(StringBuilder notesBuffer, OperationContext context) {
List<String> values = getAnnotationValues(context, OperationContext::findControllerAnnotation);
if (!values.isEmpty()) {
notesBuffer.append("<p />").append("class: ").append(String.join(",", values));
}
}
private void getMethodAnnotationNote(StringBuilder notesBuffer, OperationContext context) {
List<String> values = getAnnotationValues(context, OperationContext::findAnnotation);
if (!values.isEmpty()) {
notesBuffer.append("<p />").append("method: ").append(String.join(",", values));
}
}
private <T, R> List<String> getAnnotationValues(T target, BiFunction<T, Class<? extends Annotation>, Optional<R>> findAnnotation) {
List<String> values = new ArrayList<>();
Optional<R> postAuthorize = findAnnotation.apply(target, PostAuthorize.class);
if (postAuthorize.isPresent()) {
values.add(((PostAuthorize) postAuthorize.get()).value());
}
Optional<R> postFilter = findAnnotation.apply(target, PostFilter.class);
if (postFilter.isPresent()) {
values.add(((PostFilter) postFilter.get()).value());
}
Optional<R> preAuthorize = findAnnotation.apply(target, PreAuthorize.class);
if (preAuthorize.isPresent()) {
values.add(((PreAuthorize) preAuthorize.get()).value());
}
Optional<R> preFilter = findAnnotation.apply(target, PreFilter.class);
if (preFilter.isPresent()) {
values.add(((PreFilter) preFilter.get()).value());
}
return values;
}
}
2 Apache Shiro 注解展示
将Apache Shiro的RequiresRoles
、RequiresPermissions
的注解信息追加到接口描述中.
import com.google.common.base.Optional;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1001)
public class ShiroOperationBuilderPlugin implements OperationBuilderPlugin {
private static final String HTML_P = "<p />";
private static final String PERM = "权限:";
private static final String ROLE = "角色:";
@Override
public void apply(OperationContext context) {
String notes = context.operationBuilder().build().getNotes();
StringBuilder notesBuilder = new StringBuilder(notes == null ? "" : notes);
getClassAnnotationNote(notesBuilder, context);
getMethodAnnotationNote(notesBuilder, context);
context.operationBuilder().notes(notesBuilder.toString());
}
@Override
public boolean supports(DocumentationType delimiter) {
return true;
}
private void getClassAnnotationNote(StringBuilder notesBuffer, OperationContext context) {
List<String> values = getAnnotationValues(context, OperationContext::findControllerAnnotation);
if (!values.isEmpty()) {
notesBuffer.append(HTML_P).append("class: ").append(HTML_P).append(String.join("", values));
}
}
private void getMethodAnnotationNote(StringBuilder notesBuffer, OperationContext context) {
List<String> values = getAnnotationValues(context, OperationContext::findAnnotation);
if (!values.isEmpty()) {
notesBuffer.append(HTML_P).append("method: ").append(HTML_P).append(String.join("", values));
}
}
private <T, R> List<String> getAnnotationValues(T target, BiFunction<T, Class<? extends Annotation>, Optional<R>> findAnnotation) {
List<String> values = new ArrayList<>();
Optional<R> permissions = findAnnotation.apply(target, RequiresPermissions.class);
if (permissions.isPresent()) {
RequiresPermissions requiresPermissions = (RequiresPermissions) permissions.get();
values.add(HTML_P + PERM + getAnnotationNote(requiresPermissions.value(), requiresPermissions.logical()));
}
Optional<R> roles = findAnnotation.apply(target, RequiresRoles.class);
if (roles.isPresent()) {
RequiresRoles requiresRoles = (RequiresRoles) roles.get();
values.add(HTML_P + ROLE + getAnnotationNote(requiresRoles.value(), requiresRoles.logical()));
}
return values;
}
private String getAnnotationNote(String[] values, Logical logical) {
if (logical.equals(Logical.AND)) {
return String.join(" && ", values);
} else {
return String.join(" || ", values);
}
}
}
3 Controller演示
3.1 spring security
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/swagger")
@Api(tags = "security 注解权限展示")
@PostAuthorize("hasAuthority('class')")
@PostFilter("hasAuthority('class')")
@PreAuthorize("hasAuthority('class')")
@PreFilter("hasAuthority('class')")
public class SecuritySwaggerController {
@GetMapping("/security")
@ApiOperation(value = "security", notes = "Spring Security注解追加到接口描述")
@PostAuthorize("hasAuthority('method')")
@PostFilter("hasAuthority('method')")
@PreAuthorize("hasAuthority('method')")
@PreFilter("hasAuthority('method')")
public String security() {
return "hello security";
}
}
3.2 apache shiro
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/swagger")
@Api(tags = "shiro 注解权限展示")
@RequiresRoles(value = {"class:role1","class:role2"})
@RequiresPermissions(value = {"class:prem1","class:perm2"}, logical = Logical.OR)
public class ShiroSwaggerController {
@GetMapping("/shiro")
@ApiOperation(value = "shiro", notes = "Apache Shiro注解追加到接口描述")
@RequiresRoles(value = {"method:role1","method:role2"})
@RequiresPermissions(value = {"method:prem1","method:perm2"}, logical = Logical.OR)
public String shiro() {
return "hello shiro";
}
}
4 效果展示
参考:https://blog.csdn.net/qq_34347620/article/details/128470082,在此基础上做了一些改进。