【问题标题】:Spring Boot web app w/ both session + CSRF & stateless Basic Auth w/o CSRFSpring Boot web app w/session + CSRF & stateless Basic Auth w/o CSRF
【发布时间】:2015-09-17 16:15:50
【问题描述】:

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

有人知道怎么设置吗?我见过很多使用其中一种的例子,但不能同时使用。

【问题讨论】:

    标签: spring-security spring-boot csrf basic-authentication


    【解决方案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-02-17
      • 2017-04-17
      • 2019-06-07
      • 2015-10-03
      • 1970-01-01
      • 2014-11-29
      • 2020-08-09
      • 2015-05-22
      • 2016-06-19
      相关资源
      最近更新 更多