Какова эквивалентная конфигурация Java для тега Spring Security <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-подходе. Документация немного краткая.