根据用户角色以醒目的方式列出api [英] list the api in swagger based on user roles

查看:38
本文介绍了根据用户角色以醒目的方式列出api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,我想根据用户角色以醒目的方式列出api方法.

I have a requirement where I want to list the api methods in swagger based on user roles.

例如:-

  • 具有基本访问权限的用户A可以使用有限的api方法.
  • 具有管理员访问权限的用户B可以使用所有列出的api方法.

我不知道该怎么实现.

我正在使用 Swashbuckle.AspNetCore Version ="1.0.0"

推荐答案

可能的解决方案:

  1. 在您的swagger配置中使用不同的组名定义多个码头

@Bean
public Docket api1() {
    ...
    return new Docket(DocumentationType.SWAGGER_2)
            ...
            .groupName("api1")
            ...
            .paths(PathSelectors.ant("/api/api1Url/**"))
            .build().apiInfo(metaData());
}

@Bean
public Docket api2() {
    ...
    return new Docket(DocumentationType.SWAGGER_2)
            ...
            .groupName("api2")
            ...
            .paths(PathSelectors.ant("/api/api2Url/**"))
            .build().apiInfo(metaData());
}

  1. 定义您自己的 DocumentationCache ,它会覆盖Swagger的文档
  1. Define your own DocumentationCache which overrides Swagger's one

@Primary
@Component
public class RolesAwareDocumentationCache extends DocumentationCache {

    private final Map<String, Set<String>> allowedResourcesPerRole =
            Map.of(SecurityConfig.API1_ROLE, Collections.singleton("api1"),
                    SecurityConfig.API2_ROLE, Collections.singleton("api2"),
                    SecurityConfig.SOME_ADMIN_ROLE, Set.of("api1", "api2"));

    @Override
    public Map<String, Documentation> all() {
        var documentationMap = super.all();
        return documentationMap.entrySet().stream()
                .filter(e -> isAllowedForRole(e.getKey())) // check if has access to this group
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    private boolean isAllowedForRole(String groupName) {
        var userAuthorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream()
                .map(Object::toString)
                .collect(Collectors.toUnmodifiableSet());

        return userAuthorities.stream()
                .map(allowedResourcesPerRole::get) // get allowed resources for all of the user roles
                .filter(Objects::nonNull)
                .flatMap(Collection::stream) // flatMap to collection
                .anyMatch(s -> s.contains(groupName)); // check if result collection has specified group name
    }

}

因此,此缓存将根据安全上下文中当前用户的角色返回组.实际上,您可以使用任何规则来限制对不同组的访问.

So this cache will return groups based on the current user's role from the security context. You can actually use any rules to restrict access to different groups.

也不要忘记为 HttpSecurity 定义适当的权限,以限制对不允许角色的API的调用.

Also do not forget to define proper permissions for HttpSecurity to restrict the invocation of an API for not allowed roles.

这篇关于根据用户角色以醒目的方式列出api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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