Spring REST Security:仅在特定端点上启用基本身份验证

Ash*_*iya 4 java spring spring-mvc spring-security spring-restcontroller

我已经为我的REST API配置了Spring Security(使用HeaderHttpSessionStrategy).

我的'WebSecurityConfigurerAdapter'实现如下所示.

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

        http

            .csrf().disable()

            .authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/**").permitAll()

                .and()
            .requestCache()
                .requestCache(new NullRequestCache())
                .and()

            .httpBasic()
            ;

    }
Run Code Online (Sandbox Code Playgroud)

现在,我如何配置'HttpSecurity'对象,以便只有特定端点才能进行基本身份验证.

例如:

/ user/login:只能在此端点进行基本身份验证.在进行成功身份验证后,将返回x-auth-token标头.

/ user/create:客户端不应该能够在此端点上进行身份验证.只能返回401.Can只能使用/ user/login端口创建的"x-auth-token"访问.

sof*_*ang 6

您可以定义多个WebSecurityConfigurerAdapters.具有请求匹配器以限制适用性的优先级之一/user/login:http.requestMatcher(new AntPathRequestMatcher("/user/login"))和另一个作为其余部分的全部内容.您可以省略requestMatcher使http定义不受限制.