6

我通过spring boot使用spring security。我有两种休息服务。

public/** --> 每个人都可以访问和使用这些服务

secure/** --> 只有经过身份验证的用户才能使用。

@Slf4j
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(WebSecurity webSecurity) throws Exception {
    webSecurity.ignoring().antMatchers("/public/**");
}

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

    http.addFilterBefore(requestHeaderAuthenticationFilter(authenticationManager()),
            BasicAuthenticationFilter.class)
            .authorizeRequests().antMatchers("/secure/**").fullyAuthenticated();
}

@Bean
public RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter(
        final AuthenticationManager authenticationManager) {

    RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
    filter.setAuthenticationManager(authenticationManager);
    filter.setExceptionIfHeaderMissing(true);
    filter.setPrincipalRequestHeader("MY_HEADER");
    filter.setInvalidateSessionOnPrincipalChange(true);
    filter.setCheckForPrincipalChanges(false);
    filter.setContinueFilterChainOnUnsuccessfulAuthentication(false);
    return filter;
}

当我想访问公共资源时,我遇到了异常。

异常:“org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException”

消息:“请求中未找到 MY_HEADER 标头。”

为什么我的过滤器在配置为忽略资源时在公共资源下激活?

谢谢是提前

4

1 回答 1

2

当使用 Beans 作为过滤器时,这是Spring Security GithubWebSecurity.ignoring()中讨论的一个问题。

@Bean您可以通过删除过滤器声明中的注释来解决此问题。

// @Bean - Remove or Comment this
public RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter(
        final AuthenticationManager authenticationManager) {

    RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
    filter.setAuthenticationManager(authenticationManager);
    filter.setExceptionIfHeaderMissing(true);
    filter.setPrincipalRequestHeader("MY_HEADER");
    filter.setInvalidateSessionOnPrincipalChange(true);
    filter.setCheckForPrincipalChanges(false);
    filter.setContinueFilterChainOnUnsuccessfulAuthentication(false);
    return filter;
}
于 2016-12-09T15:59:01.140 回答