【发布时间】:2023-02-04 14:51:11
【问题描述】:
我正在使用 Spring Security 来验证我的 GET 和 POST 请求。 GET 和POST 的授权机制不一样。下面的 sn-p 来自我的SecurityConfigs 配置方法。
FilterA 用于 GET 请求,我定义了一个 customBAuthenticationManager bean,它为它实现了 AuthenticationManager。
FilterB 用于POST 请求,我已经用UserDetails 服务定义了customAuthProvider。这些 GET 和 POST 请求在单独添加时工作正常。但是当这两个过滤器一个接一个地添加时,过滤器链中的第一个请求失败但第二个请求工作正常。
例如,使用下面的代码,我的POST 请求工作正常但GET 请求(链中的第一个)抛出 401 错误。如果我交换 GET 和 POST 的顺序,那么 GET 可以正常工作,但 POST(链中的第一个)会抛出 403 错误。
但在所有情况下,我都可以看到自定义身份验证管理器/提供程序工作正常。
有人可以帮我了解这里出了什么问题吗?
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
FilterA filtera = new FilterA();
filtera.setCheckForPrincipalChanges(true);
filtera.setAuthenticationManager(customBAuthenticationManager());
FilterB filterb = new FilterB();
filterb.setCheckForPrincipalChanges(true);
filterb.setAuthenticationManager(authenticationManager());
httpSecurity
.headers()
.frameOptions()
.disable()
.and()
.mvcMatcher("/**")
.csrf()
.disable()
.requestCache()
.requestCache(getHttpSessionRequestCache())
.and()
.sessionManagement()
.maximumSessions(1)
.and()
.and()
.addFilter(filtera)
.authorizeRequests()
.mvcMatchers("/getrequest/**").authenticated()
.and()
.addFilter(filterb)
.authenticationProvider(customAauthProvider())
.authorizeRequests()
.mvcMatchers("/postrequest/**").authenticated()
.and()
.authorizeRequests()
.mvcMatchers("/different-open-request/**").permitAll()
.and()
.httpBasic();
尝试更改过滤器链中过滤器的顺序。尝试从过滤器链中删除其中一个请求,效果很好。
【问题讨论】:
-
你能分享
FilterA和FilterB吗?
标签: java spring spring-boot rest spring-security