一文解决Security中访问静态资源和web.ignoring()和perimitAll()不起作用

本文参考

【1】江南一点雨的SpringSecurity配置
【2】WebMvcConfiguer配置

问题需求

学习微人事项目中,我想在后端加入静态资源,我的静态资源就在static目录下,可怎么配置都返回需要权限认证,调试后发现,如下代码访问的所有路径,都会进到FilterInvocationSecurityMetadataSource中进行处理,松哥原话

getAttributes(Object o)方法返回null的话,意味着当前这个请求不需要任何角色就能访问,甚至不需要登录

在这里插入图片描述
代码可修改如下(初始版本),后有通用解决方案

@Component
public class CusomFilterIncovationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    MenuService menuService;
    // ant路径匹配的类
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        List<Menu> menus = menuService.getAllMenusRole();
        System.out.println("开始匹配路径");
        for(Menu menu: menus){
            if(antPathMatcher.match(menu.getUrl(), requestUrl)){
                List<Role> roles = menu.getRoles();
                String[] str = new String[roles.size()];
                for(int i=0; i<roles.size();i++){
                    str[i] = roles.get(i).getName();
                }
                return SecurityConfig.createList(str);
            }
        }
        //静态资源配置,返回null表示不要任何角色即可访问
        for(String url: StaticSource.source){
            //System.out.println(url);
            //System.out.println(requestUrl);
            if(antPathMatcher.match(url,requestUrl)){
                return null;
            }
        }
        // 标记而已
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    // 不用管
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    @Override
    /**
     * @param:
     * authentication 用户登陆信息
     * collection Filter的返回值
     */
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        //System.out.println(collection.size());
        //System.out.println(collection);
        // 修改内容
        if(collection == null || collection.isEmpty()){
            return;
        }
        for(ConfigAttribute configAttribute: collection){
            String needRole = configAttribute.getAttribute();
            if("ROLE_LOGIN".equals(needRole)){
                // 判断用户是否登陆
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw  new AccessDeniedException("尚未登陆,请登陆");
                }else{
                    return;
                }
            }
            Collection<? extends GrantedAuthority>authorities = authentication.getAuthorities();
            // A,B两个角色有一个即可访问
            for (GrantedAuthority authority:authorities) {
                // 匹配到角色,立刻返回
                if(authority.getAuthority().equals(needRole)){
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足,请联系管理员");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
public class StaticSource {
     public static final String[] source = new String[]{"/img/**","/js/**","/css/**","/favicon.ico"};
}
通用解决
 // 不起作用的配置
 @Override
 public void configure(WebSecurity web) throws Exception {
     web.ignoring().antMatchers("/img/**");
 }
 protected void configure(HttpSecurity http) throws Exception {
 	http.authorizeRequests().antMatchers("/img/**").permitAll()
 }

根据参考资料【2】的描述,在SpringBoot2.0中WebMvcConfigurerAdapter已被废弃,访问静态资源就会被HandlerInterceptor拦截,为了防止静态资源被拦截,我们需要实现自己的inteceptor的规则

通用解决方案:

// 创建自己的拦截器类,实现HandlerInterceptor 接口
public class MyInterceptor implements HandlerInterceptor {
}
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/swagger-ui.html","/js/**","/css/**","/img/**");
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
### 回答1: web.ignoring().antMatchers()是Spring Security的一种配置方式,用于忽略某些URL的安全性检查。其ignoring()方法表示忽略某些URL,而antMatchers()方法则指定了需要忽略的URL的匹配规则。具体来说,antMatchers()方法可以接受一个或多个URL模式,用于匹配需要忽略的URL。例如,antMatchers("/public/**")表示忽略所有以/public/开头的URL。 ### 回答2: 在使用Spring Security框架进行Web应用程序的安全配置时,`.ignoring().antMatchers()`是一种用于忽略特定URL或路径的方法。 `.antMatchers()`是一个用于匹配URL或路径的方法。我们可以使用`.antMatchers()`来指定一组URL或路径的模式,并将其与当前请求的URL进行匹配。如果请求的URL与任何一个`.antMatchers()`指定的模式匹配成功,该URL将被认为是匹配的,并相应地进行安全处理。 `.ignoring()`则用于告诉Spring Security框架在处理匹配上述`.antMatchers()`的URL时忽略相关的安全配置。这意味着,即使请求的URL匹配成功,Spring Security也不会对该URL进行安全验证或拦截。 通常,我们使用`.ignoring().antMatchers()`来配置一些不需要进行安全验证或拦截的URL或路径。这些URL可能是一些静态资源文件,例如CSS、JavaScript或图像文件等,或者是一些公开访问的页面或API。 例如,我们可以使用以下代码来忽略所有静态资源文件的安全验证: ``` @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/css/**", "/js/**", "/images/**"); } ``` 这样,所有以`/css/`、`/js/`或`/images/`开头的URL路径将被忽略安全验证。对于这些URL,Spring Security将允许访问而不进行任何额外的安全处理。 总而言之,`.ignoring().antMatchers()`是一种在Spring Security用于忽略URL或路径,从而避免进行安全验证和拦截的方法。 ### 回答3: web.ignoring() .antMatchers实际上是Spring Security框架用于配置忽略某些特定请求路径的方法。在WebSecurityConfigurerAdapter配置类的configure方法,可以使用这个方法来指定一些URL路径忽略安全控制。 web.ignoring()方法的.antMatchers()用于指定要忽略的路径,可以使用Ant风格的路径匹配方式来匹配多个URL路径模式。路径模式可以使用通配符*来表示任意字符或者?来表示一个字符。 例如,如果我们想要忽略对所有以/static/开头的URL进行安全控制,可以使用web.ignoring().antMatchers("/static/**")来实现。这样配置后,访问以/static/开头的URL时,将不会触发Spring Security的认证和授权流程。 这个方法常用于配置一些静态资源路径,比如CSS、JS、图片等,或者是一些公开的API接口路径,不需要进行身份验证和权限校验的路径。 需要注意的是,忽略路径的配置应该放在其他需要进行安全控制的配置之前,这样才能确保这些路径被正确地忽略掉。 总之,web.ignoring().antMatchers()的作用是配置Spring Security框架忽略某些特定请求路径,不对其进行安全控制。通过这个方法可以细粒度地控制哪些路径需要安全控制,哪些路径可以被忽略。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值