【问题标题】:How to enable Java Spring security only on paths defined in certain controller?如何仅在某些控制器中定义的路径上启用 Java Spring 安全性?
【发布时间】:2020-02-11 22:05:24
【问题描述】:

我想使用我的自定义过滤器启用 Spring Security,但我发现我无法仅在控制器中定义的路径上启用它。

这是我当前的安全配置:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .antMatcher("/api/v1/**").addFilterBefore(
                    new AuthenticationFilter(myAuthenticator()),
                    ChannelProcessingFilter.class);

    }
}

在我的控制器中,我有 /api/v1/user、/api/v1/user/{userId}。当我尝试访问无效路径时,例如/api/v1/invalid,我总是得到 401 而不是 404,因为任何以 /api/v1 开头的路径都会首先通过 AuthenticationFilter。当我尝试在现有路径上使用不受支持的 HTTP 方法时也会发生这种情况,我的应用程序将返回 401 而不是 405。

我想实现类似在控制器级别(或方法级别也可以)添加注释,并仅在该控制器中定义的路径上应用身份验证过滤器,例如

@WhateverAnnotationWillAddFilterToThisController***
@RestController
@RequestMapping(value = "/api/v1", produces = "application/json")
public interface LicensingController {

    @RequestMapping(value = "user", method = RequestMethod.POST)
    public ResponseEntity<?> user();

    @RequestMapping(value = "user/{userId}", method = RequestMethod.GET)
    public ResponseEntity<LicensingRequest> getUser(
        @PathVariable
        String userId);
}

任何建议将不胜感激。谢谢!

【问题讨论】:

    标签: java spring spring-security spring-security-rest


    【解决方案1】:

    该行为是正确且一致的,因为您使用/api/v1/** 来确保安全,这是一条更广泛的路径。理想情况下,AuthenticationFilter 始终位于资源路径之上,以避免在未经身份验证的情况下访问资源。

    为了获得 404,您所做的是使用更窄的路径匹配。

    @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    
            http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .antMatchers("/api/v1/user", "/api/v1/user/{userId}").addFilterBefore(
                        new AuthenticationFilter(myAuthenticator()),
                        ChannelProcessingFilter.class);
    
        }
    }
    

    如果你想要 http 方法级别的限制,你也必须指定。

    【讨论】:

    • 谢谢!这肯定会奏效。但是我想做的更像是一个控制器中有 30 个 api,很难指定所有路径,如果开发人员忘记将新 api 添加到 antMatchers 中,很容易让新 api 不安全。因此,如果存在类/控制器级别的安全性,我可以在类级别对其进行保护,以便该类中定义的所有路径都将受到保护,但未实现的路径将不受保护。这可能吗?
    猜你喜欢
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    • 2013-01-08
    相关资源
    最近更新 更多