首页 > 解决方案 > 如何使用spring security允​​许spring boot maven的静态文件夹中的所有资源?

问题描述

我正在创建一个应用程序,使用 angular 作为前端,使用 spring boot 作为后端。我出于安全目的使用 spring-boot-security 。

Spring Boot 从src/main/resources/static文件夹中提供静态内容。我将 angular dist 文件夹的所有内容放在这里,即所有 js,css,html 由ng build.

但是在运行该应用程序时,我不断收到 401 未经授权的错误。这是我的configure()方法:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .cors()
                .and()
                .exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                .and()
                .authorizeRequests()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                .antMatchers("/api/v1/login/").permitAll()
                    .anyRequest().authenticated()
                .and()
                .addFilter(getJWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()));
    }

如果我添加.antMatchers("/**").permitAll(),那么该应用程序将正确加载所有角度资源,但会使安全性变得无用,因为所有 api 端点都会被暴露。

我还读到\css,\images,\js默认情况下允许等,但在这里我只是指静态文件夹。我还尝试将所有内容移动到新端点,例如/app通过实现addResourceHandlers()方法,但随后我的角度代码中断,因为它引用了所有 css ,jss 直接在其 href 中,而不是在任何文件夹名称后面。

我正在使用 spring boot 2.1.1 版本,大多数答案都是指 spring boot v1,我找不到解决方案。

我想配置 spring security 以允许访问static文件夹下的所有资源。这样做可以让我在不更改所有 href 的情况下使用我的角度代码。我怎样才能做到这一点?

标签: spring-bootspring-security

解决方案


推荐阅读