【问题标题】:How to enable spring security session management for specific url如何为特定 url 启用 spring 安全会话管理
【发布时间】:2021-06-01 15:56:03
【问题描述】:

我有一个场景,我必须实施 Spring Security 来保护已经存在的其他端点中的新端点。

我目前的配置如下:

protected void configure(HttpSecurity http) throws Exception {
    http.addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
        .csrf().requireCsrfProtectionMatcher(new CsrfRequestMatcher())
        .and()
        .sessionManagement().invalidSessionUrl("/invalidSession")
        .and()
        .sessionManagement().maximumSessions(1).expiredUrl("/expiredSession").and()
        .and()
        .authorizeRequests()
            .antMatchers("/user/manage/*").authenticated()
            .anyRequest().permitAll()
            .and()
        .formLogin()
            .loginPage("/user/login").permitAll()
            .defaultSuccessUrl("/user/manage")
            .and()
        .logout().permitAll();
}

我的要求是仅对 /user/manage/* 路径强制执行上述 spring 安全配置。但是,我注意到我的应用程序中的其他 mvc 端点会导致重定向到 /invalidSessions URL。

我希望其他端点按原样工作,并完全禁用这些端点的 Spring Security(以及会话管理指令)。我知道这样做的唯一地方是在提供的其他配置覆盖中,但它并不完全符合我的需要:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/cof/manage/*"); //need something like NOT "/cof/manage/*"
}

上面的忽略可以在每个 url 的基础上完成,但不可能禁用除给定 URL 之外的所有 URL。除了“/cof/manage/*”路径之外,我唯一的选择是列出我的应用程序中当前存在的所有 MVC 端点吗?

谢谢

【问题讨论】:

    标签: spring spring-mvc spring-security


    【解决方案1】:

    这个问题有点用词不当,因为您不想仅禁用会话管理,而是完全针对特定 URL 启用安全性(仅禁用会话管理本身是不可能的;它需要为不同的网址。

    正如您已经说过的,可以完全禁用 URL 的 spring 安全性,这也可以通过 NegatedRequestMatcher 排除:

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().requestMatchers(new NegatedRequestMatcher(new AntPathRequestMatcher("/cof/manage/*")));
    }
    

    【讨论】:

    • 嗨。感谢您的信息。我不知道存在。但是,我让我的场景以不同的方法工作。只需在configure(HttpSecurity http) 方法中以http.antMatcher("/cof/manage/**") 开头,因此整个配置仅适用于上述路径
    猜你喜欢
    • 1970-01-01
    • 2013-12-01
    • 2013-10-03
    • 1970-01-01
    • 2013-07-02
    • 2015-07-19
    • 2018-01-16
    • 1970-01-01
    • 2016-05-05
    相关资源
    最近更新 更多