如何在 Spring 端点的 Swagger UI 中显示所需的用户角色(访问控制信息)? [英] How to display required user roles (access control information) in Swagger UI for Spring's endpoints?

查看:30
本文介绍了如何在 Spring 端点的 Swagger UI 中显示所需的用户角色(访问控制信息)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 Spring 中制作的 rest api,并且正在使用 Swagger 来编写文档.最近实施了基于令牌的身份验证.在令牌中,有(内部)用户的角色(权限).每个控制器都用几个 Swagger 注释和一个 @PreAuthorize(some roles..) 注释,如下所示:

I have a rest api made in Spring and am using Swagger for documentation. Recently a token based authentication was implemented. In the token, there are (internal) user's roles (authorities). Each controller is annotated with a couple of Swagger annotations and a @PreAuthorize(some roles..) like so:

@ApiOperation("Delete user")
@ApiResponses(value = {
        @ApiResponse(code = 404, message = "User not found", response = ErrorResponse.class)
})
@PreAuthorize("hasAuthority('ADMIN')")
@DeleteMapping(value = "/{id}")
public ResponseEntity<?> deleteUser(@PathVariable UUID id) {
    userService.delete(id);
    return ResponseEntity.ok().build();
}

现在,我不知道如何在我的 swagger-ui 中显示这些角色,因此每个端点都有信息,需要什么用户角色才能访问它.我浏览了互联网,发现只有一些非常模糊的信息,其中大部分与 Spring 完全无关.

Now, I have no idea how I can display in my swagger-ui those roles, so each endpoint has information, what user role is required to access it. I have browsed the internet and found only some really vague information, most of it not concerning Spring at all.

注意:我尝试使用 notes: @ApiOperation(value = "Delete user", notes = "Required roles: ADMIN, USER") 来显示自定义文本,但这似乎不是正确的方法.

Note: I tried using notes: @ApiOperation(value = "Delete user", notes = "Required roles: ADMIN, USER") to display custom text, but this doesn't seem like a right way to go.

推荐答案

这是我的个人版本,从@Unni版本开始,我只是玩了一点html标记.

This is my personal version started from @Unni version, I just played a little bit with html markup.

@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1)
public class OperationNotesResourcesReader implements OperationBuilderPlugin {
    private static final Logger LOG = Logger.getLogger(OperationNotesResourcesReader.class.getName());

    private final DescriptionResolver descriptions;

    @Autowired
    public OperationNotesResourcesReader(DescriptionResolver descriptions) {
        this.descriptions = descriptions;
    }

    @Override
    public void apply(OperationContext context) {
        try {
            StringBuilder sb = new StringBuilder();

            // Check authorization
            Optional<PreAuthorize> preAuthorizeAnnotation = context.findAnnotation(PreAuthorize.class);
            sb.append("<b>Access Privileges & Rules</b>: ");
            if (preAuthorizeAnnotation.isPresent()) {
                sb.append("<em>" + preAuthorizeAnnotation.get().value() + "</em>");
            } else {
                sb.append("<em>NOT_FOUND</em>");
            }

            // Check notes
            Optional<ApiOperation> annotation = context.findAnnotation(ApiOperation.class);
            if (annotation.isPresent() && StringUtils.hasText(annotation.get().notes())) {
                sb.append("<br /><br />");
                sb.append(annotation.get().notes());
            }

            // Add the note text to the Swagger UI
            context.operationBuilder().notes(descriptions.resolve(sb.toString()));
        } catch (Exception e) {
            LOG.log(Level.SEVERE, "Error when creating swagger documentation for security roles: ", e);
        }
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }
}

这是最终的渲染:

这篇关于如何在 Spring 端点的 Swagger UI 中显示所需的用户角色(访问控制信息)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆