Spring Security 如何正确配置过滤器链中的Spring安全白色列表?

ufj5ltwl  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(278)

我试图建立一个安全过滤链,并允许一些白色名单通过没有安全
这是我的依赖

implementation 'org.springframework.boot:spring-boot-starter-security:3.1.5'

字符串
我的过滤器

private static final String[] WHITE_LIST_URL = {"/ping/getEnvironment"};

    public SecurityFilterChain securityFilterChain(HttpSecurity http) {
        try {
            http.csrf(AbstractHttpConfigurer::disable)
                    .authorizeHttpRequests(req -> req.requestMatchers(WHITE_LIST_URL)
                            .permitAll()
                            .anyRequest()
                            .authenticated())
                    .sessionManagement(session -> session.sessionCreationPolicy(STATELESS))
                    .authenticationProvider(authenticationProvider)
                    .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
            return http.build();
        } catch (Exception e) {
            throw new IllegalStateException("Not able to build security filter chain", e);
        }
    }


我的测试

@Test
    void getEnvironmentTest() throws Exception {
        String rawResponse = mockMvc.perform(MockMvcRequestBuilders.get("/ping/getEnvironment"))
                .andExpect(MockMvcResultMatchers.status()
                        .isOk())
                .andReturn()
                .getResponse()
                .getContentAsString();

        ObjectMapper objectMapper = new ObjectMapper();

        PingResponse pingResponse = objectMapper.readValue(rawResponse, PingResponse.class);
        Assertions.assertNotNull(pingResponse);
    }


但这种方法失败了,

MockHttpServletResponse:
           Status = 401
    Error message = Unauthorized
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", WWW-Authenticate:"Basic realm="Realm"", X-Content-Type-Options:"nosniff", X-XSS-Protection:"0", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Status
Expected :200
Actual   :401


如你所见,我得到了401而不是200

ltqd579y

ltqd579y1#

我发现了。我缺少@Bean注解。在添加@Bean之后,我的测试按预期通过了
这是我的安全过滤器chahin看起来像包括过滤器anotation。

package eu.vxbank.api.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity
public class SecurityConfiguration {

    private final AuthenticationProvider authenticationProvider; // from spring
    private final JwtAuthenticationFilter jwtAuthFilter; // my filter

    private static final String[] WHITE_LIST_URL = {"/ping/getEnvironment"};

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) {
        try {
            http.csrf(AbstractHttpConfigurer::disable)
                    .authorizeHttpRequests(req -> req.requestMatchers(WHITE_LIST_URL)
                            .permitAll()
                            .anyRequest()
                            .authenticated())
                    .sessionManagement(session -> session.sessionCreationPolicy(STATELESS))
                    .authenticationProvider(authenticationProvider)
                    .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
            return http.build();
        } catch (Exception e) {
            throw new IllegalStateException("Not able to build security filter chain", e);
        }
    }
}

字符串

相关问题