如何使用Java配置来表示Spring Security的“自定义过滤器”?
2022-09-01 12:00:42
Spring Security 标签的等效 Java 配置是什么?<custom-filter>
<http>
<custom-filter position="FORM_LOGIN_FILTER" ref="myFilter"/>
</http>
我试过了
http.addFilter( new MyUsernamePasswordAuthenticationFilter() )
其中,类扩展了默认筛选器,但它始终使用默认值。formLogin
我的过滤器:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
// proof of concept of how the http.addFilter() works
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
System.out.println("running my own version of UsernmePasswordFilter ... ");
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
}
相关配置件:
@Configuration
@EnableWebMvcSecurity // annotate class configuring AuthenticationManagerBuilder
@ComponentScan("com.kayjed")
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**","/signup").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
http.addFilter(new MyUsernamePasswordAuthenticationFilter());
}
...
}
在调试器中运行 MVC 应用始终显示从默认值开始的登录尝试身份验证,而不是我打算使用该类。UsernamePasswordAuthenticationFilter
MyUsernamePasswordAuthenticationFilter
无论如何,我不是试图让某人调试代码;相反,我希望看到一个使用Java配置的好例子,它执行XML方法中的自定义过滤器元素的等效操作。文档有点简洁。