首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在spring安全和JWT中应用动态ACL

在spring安全和JWT中应用动态ACL
EN

Stack Overflow用户
提问于 2022-03-15 23:14:38
回答 1查看 256关注 0票数 0

我使用SpringSecurity、JWT和OAuth2实现了身份验证。

代码语言:javascript
运行
复制
@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers(HttpMethod.POST,"/v1/register").permitAll()
    .antMatchers(HttpMethod.GET,"/v1/public").permitAll();
    List<String> permisos = roleService.findPermisos();
    for(String name: permisos) {
        String[] data = name.split(",");
        http.authorizeRequests().antMatchers(data[0], data[1]).hasRole(data[2]);
    }
    http.authorizeRequests()
    .anyRequest().authenticated()
    .and().cors().configurationSource(corsConfigurationSource());
}

目前,configure(HttpSecurity http)方法在OAuth2端工作。在我的数据库中,每个角色都被允许或拒绝访问它们的所有@RestController,问题是,只有在编译了应用程序之后才应用它,而我需要的是在修改允许或拒绝访问时应用它,而不需要重新编译List<String> permisos = roleService.findPermisos()中显示的动态acl。

搜索我读到,我可以使用过滤器与HttpSecurity,我一直未能找到例子,请您的帮助。

EN

Stack Overflow用户

发布于 2022-03-21 03:01:56

通过一些研究,我修改了我的解决方案如下:

代码语言:javascript
运行
复制
@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers(HttpMethod.PUT,"/v1/menu").permitAll()
    .anyRequest().authenticated().and()
    .addFilterAfter(new CustomFilter(), AbstractPreAuthenticatedProcessingFilter.class)
    .cors().configurationSource(corsConfigurationSource());
}

我添加了一个过滤器addFilterAfter(new CustomFilter(), AbstractPreAuthenticatedProcessingFilter.class),在CustomFilter()中是:

代码语言:javascript
运行
复制
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        ServletContext servletContext = request.getServletContext();
        if(usuarioService == null){
            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            usuarioService = webApplicationContext.getBean(IUsuarioService.class);
        }
        String[] path = request.getRequestURI().split("/");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Usuario usuario = usuarioService.findByEmail(authentication.getName());
        if(usuarioService.existsPermission(request.getMethod(), path[2], authentication.getName())) {
            filterChain.doFilter(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
}

所以我把我的解决方案从循环改为通过过滤器查询,问题是所有其他的都必须注册和验证,这将是允许访问我不希望被验证的资源的问题。

如果你有更好的解决方案,我会非常感谢你的帮助。

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71490064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档