在Spring Security中提供静态资源-允许访问'/resources/public'中的所有文件 [英] Serving static resources in spring security - Allow access to all files in '/resources/public'

查看:243
本文介绍了在Spring Security中提供静态资源-允许访问'/resources/public'中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过此设置,我可以很好地提供静态资源,但是我必须逐个文件地定义允许提供的文件.

I can serve static resources perfectly fine with this setup however I have to define on a file by file basis the files which are allowed to be served.

我当前的用例是/resources/public/目录中的任何内容都应允许客户端访问.

My current use case is anything located in the /resources/public/ directory should have allowed access by clients.

我尝试了一个班轮/resources/public/**/public/**,但仍然不允许访问我获得403的所有公共资源.因此,在我的http配置中,我已经开始定义允许的文件扩展名,但是我不喜欢这种方法,因为我的Web应用程序中有很多不同的扩展名.

i've tried the one liner /resources/public/** and /public/** that still doesn't allow access to all public resources i get 403's. So in my http configure i've started defining file extensions that are permitted, but i don't like that approach as there are lots of different extensions in my webapp.

我的问题是,我如何允许访问/resources/public/中的所有文件而不必为每个文件扩展名定义蚂蚁匹配器,或者我只是个小人物?

My question is how can i allow access to all files in /resources/public/ without having to define ant matchers for each file extension or am i just being petty?

Spring WebSecurityConfigurerAdapter-根据jmw5598的答案进行了编辑.

Spring WebSecurityConfigurerAdapter - edited as per jmw5598's answer.

    @Override
    public void configure(WebSecurity web) throws Exception {
           web
            .ignoring()
            .antMatchers("/resources/**");
    }


    @Override
    protected void configure(HttpSecurity http) {

            http
                .authorizeRequests()
                        .authorizeRequests()
                .antMatchers(
                    "/public/**",
                    "/.svg", "/.ico", "/.eot", "/.woff2",
                    "/.ttf", "/.woff", "/.html", "/.js",
                    "/.map", "/*.bundle.*",
                    "/index.html", "/", "/home", "/dashboard")
                .permitAll()
                .anyRequest().authenticated();
    }

用于投放网络应用的控制器:

Controller for serving web app:

@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@Controller
public class AngularWebAppController {

    @GetMapping(value = "/{path:[^\\.]*}")
    public String redirect() {
        return "forward:/";
    }

}

我在/resources

  • 根据dur的评论要求添加.
  • Added as requested by dur's comment.

推荐答案

您要请求分隔符资源或URL处理程序映射.在春天这很容易.

You want to request separator resource or URL handler mapping. this is easy in Spring.

Servelet上下文

<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
    up static resources in the ${webappRoot}/resources directory -->

<resources mapping="/resources/**" location="/resources/" />

<default-servlet-handler />

此标记允许将DispatcherServlet映射到"/"(因此 覆盖容器默认Servlet的映射),而 仍然允许静态资源请求由 容器的默认Servlet [...]

This tag allows for mapping the DispatcherServlet to "/" (thus overriding the mapping of the container's default Servlet), while still allowing static resource requests to be handled by the container's default Servlet [...]

也许这个春季安全性内容很有用.

Maybe you useful this spring security content.

CustomWebSecurityConfigurerAdapter

我们的HelloWebSecurityConfiguration示例演示了Spring Security Java配置可以为我们提供一些非常好的默认值.让我们看一些基本的自定义.

Our HelloWebSecurityConfiguration sample, demonstrates that Spring Security Java configuration can provide some very nice defaults for us. Let’s take a look at some basic customization.

@EnableWebSecurity
@Configuration
public class CustomWebSecurityConfigurerAdapter extends
   WebSecurityConfigurerAdapter {
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) {
    auth
      .inMemoryAuthentication()
        .withUser("user")  // #1
          .password("password")
          .roles("USER")
          .and()
        .withUser("admin") // #2
          .password("password")
          .roles("ADMIN","USER");
  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    web
      .ignoring()
         .antMatchers("/resources/**"); // #3
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeUrls()
        .antMatchers("/signup","/about").permitAll() // #4
        .antMatchers("/admin/**").hasRole("ADMIN") // #6
        .anyRequest().authenticated() // 7
        .and()
    .formLogin()  // #8
        .loginUrl("/login") // #9
        .permitAll(); // #5
  }
}

假设我们调整AbstractAnnotationConfigDispatcherServletInitializer来加载新配置,我们的CustomWebSecurityConfigurerAdapter将执行以下操作:

Assuming that we adjust AbstractAnnotationConfigDispatcherServletInitializer to load our new configuration, our CustomWebSecurityConfigurerAdapter will do the following:

  • 允许使用名为"user"的用户进行内存身份验证
  • 允许使用名为的管理用户进行内存身份验证 管理员"
  • 忽略任何以"/resources/"开头的请求.这类似于 使用XML名称空间时配置http @ security = none 配置.
  • 允许任何人(包括未经身份验证的用户)访问URL "/signup"和"/about"
  • 允许任何人(包括未经身份验证的用户)访问URL "/login"和"/login?error".在这种情况下,permitAll()表示, 允许访问formLogin()使用的任何URL.
  • 任何以"/admin/"开头的URL必须是管理用户. 对于我们的示例,将是用户"admin".
  • 所有剩余的URL要求用户成功 已验证
  • 使用Java配置设置基于表单的身份验证 默认值.当POST提交到服务器时执行身份验证 带有参数"username"和"password"的URL"/login".
  • 明确说明登录页面,这表示开发人员正在 请求GET/login时需要呈现登录页面.
  • Allow in memory authentication with a user named "user"
  • Allow in memory authentication with an administrative user named "admin"
  • Ignore any request that starts with "/resources/". This is similar to configuring http@security=none when using the XML namespace configuration.
  • Allow anyone (including unauthenticated users) to access to the URLs "/signup" and "/about"
  • Allow anyone (including unauthenticated users) to access to the URLs "/login" and "/login?error". The permitAll() in this case means, allow access to any URL that formLogin() uses.
  • Any URL that starts with "/admin/" must be an administrative user. For our example, that would be the user "admin".
  • All remaining URLs require that the user be successfully authenticated
  • Setup form based authentication using the Java configuration defaults. Authentication is performed when a POST is submitted to the URL "/login" with the parameters "username" and "password".
  • Explicitly state the login page, which means the developer is required to render the login page when GET /login is requested.

对于那些熟悉基于XML的配置的人,上面的配置与以下XML配置非常相似:

For those that are familiar with the XML based configuration, the configuration above is very similar to the following XML configuration:

<http security="none" pattern="/resources/**"/>
<http use-expressions="true">
  <intercept-url pattern="/logout" access="permitAll"/>
  <intercept-url pattern="/login" access="permitAll"/>
  <intercept-url pattern="/signup" access="permitAll"/>
  <intercept-url pattern="/about" access="permitAll"/>
  <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
  <logout
      logout-success-url="/login?logout"
      logout-url="/logout"
  />
  <form-login
      authentication-failure-url="/login?error"
      login-page="/login"
      login-processing-url="/login"
      password-parameter="password"
      username-parameter="username"
  />
</http>
<authentication-manager>
  <authentication-provider>
    <user-service>
      <user name="user" 
          password="password" 
          authorities="ROLE_USER"/>
      <user name="admin" 
          password="password" 
          authorities="ROLE_USER,ROLE_ADMIN"/>
    </user-service>
  </authentication-provider>
</authentication-manager>

与XML命名空间的相似性

看完我们稍微复杂一点的示例之后,您也许可以找到XML名称空间和Java配置之间的一些相似之处.以下是一些更有用的要点:

After looking at our slightly more complicated example, you might be able to find some similarities between the XML namespace and the Java configuration. Here are some of the more useful points:

  • HttpSecurity与http名称空间元素非常相似.它 允许针对特定选择配置基于Web的安全性(在 这种情况下).
  • WebSecurity与任何安全命名空间元素非常相似, 适用于网络,并且不需要父级(例如,security = none, 调试等).它允许配置影响整个Web的事物 安全.
  • WebSecurityConfigurerAdapter是一个方便的类,它允许 WebSecurity和HttpSecurity的自定义.我们可以扩展 WebSecurityConfigurerAdapter多次(在不同的对象中) 复制具有多个http元素的行为.
  • 通过格式化我们的Java配置代码,它更容易阅读. 可以类似于XML名称空间中的"and()"来读取它. 表示可以选择关闭XML元素.
  • HttpSecurity is quite similar to the http namespace element. It allows configuring web based security for a certain selection (in this case all) requests.
  • WebSecurity is quite similar to any Security namespace elements that are for the web and that do not require a parent (i.e. security=none, debug, etc). It allows configuring things that impact all of web security.
  • WebSecurityConfigurerAdapter is a convenience class that allows customization to both WebSecurity and HttpSecurity. We can extend WebSecurityConfigurerAdapter multiple times (in distinct objects) to replicate the behavior of having multiple http elements.
  • By formatting our Java configuration code it is much easier to read. It can be read similar to the XML namespace equivalent where "and()" represents optionally closing an XML element.

Spring Security Java配置预览

这篇关于在Spring Security中提供静态资源-允许访问'/resources/public'中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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