小编典典

不带会话和CSRF的Spring Boot Web应用程序,不带CSRF的无状态基本身份验证

spring-boot

我正在尝试建立一个基于Spring
Boot的Web服务器,该服务器同时支持基于会话的安全UI,包括CSRF保护和通过基本身份验证进行身份验证且不需要CSRF的无状态访问。我尝试支持的两个用例是一个标准的AngularJS
UI和一个对每个请求进行身份验证的简单REST api。

有人知道如何配置吗?我已经看到了很多使用一个或另一个但没有同时使用的示例。


阅读 275

收藏
2020-05-30

共1个答案

小编典典

因此,我终于再次回到研究这个问题,结果发现解决方案几乎和我期望的一样简单。解决方案是有两个WebSecurityConfigurerAdapter类。此处描述:

http://docs.spring.io/spring-
security/site/docs/3.2.x/reference/htmlsingle/#multiple-
httpsecurity

执行此操作时需要注意两件事:

  1. 这些WebSecurityConfigurerAdapter类必须具有不同的@Order值。因此,我用注释了其中一个@Order(1),迫使在处理HTTP请求时首先对其进行评估。在我的情况下,哪一个首先并不重要,它们必须有所不同。
  2. 这两种HttpSecurity配置需要应用于不同的URL。这是通过使用antMatcher()每个值来完成的。鉴于提供给的值@RequestMapping可以是一个URL数组,仍然有可能只有一个REST控制器方法来处理对两个URL的请求。

因此,它们是:

@Configuration
@EnableWebSecurity
@Order(1)
public class APISecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    @Order(1)
    protected void configure(HttpSecurity http) throws Exception {

        http.antMatcher("/api/**")
                .authorizeRequests()
                .anyRequest().fullyAuthenticated().and()
                .httpBasic().and()
                .csrf().disable();
    }
}

@Configuration
@EnableWebSecurity
public class UISecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/ui/**").authenticated();
    }
}
2020-05-30