【发布时间】:2014-07-30 03:06:36
【问题描述】:
Spring Security <custom-filter> 标签的等效 Java 配置是什么?
<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 方法中执行与自定义过滤器元素等效的操作。文档有点简洁。
【问题讨论】:
-
请发布您的整个配置并描述“它始终使用 formLogin 默认值”的意思
标签: java spring-security spring-java-config