在用戶身份驗證我需要檢索他的遠程地址和遠程主機。
我想實現一個自定義過濾器來支持這個,但我得到「authenticationManager必須指定」。
另一個疑問是...以編程方式註冊自定義過濾器的正確方法是什麼?如何在Spring Security中以編程方式配置自定義過濾器?
使用配置註釋:
@Configuration
@EnableWebSecurity
public class SecurityApplicationConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private SCAAuthenticationFilter scaAuthenticationFilter;
@Autowired
private SCAAuthenticationProvider scaAuthenticationProvider;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(scaAuthenticationProvider);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilter(scaAuthenticationFilter) // What is the right way ?
.addFilterBefore(scaAuthenticationFilter, AbstractAuthenticationProcessingFilter.class) // What is the right way ?
.csrf().disable()
.authorizeRequests()
.antMatchers("/manual/**").authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.failureUrl("/login?error=true")
.defaultSuccessUrl("/manual")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.permitAll()
.and();
}
}
的自定義過濾器:
@Component
public class SCAAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
String remoteHost = request.getRemoteHost();
String remoteAddr = request.getRemoteAddr();
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
SCAAuthenticationToken scaAuthenticationToken = new SCAAuthenticationToken(username, password, remoteHost, remoteAddr);
setDetails(request, scaAuthenticationToken);
return getAuthenticationManager().authenticate(scaAuthenticationToken);
}
}
的'addFilter'和'addFilterBefore'行爲應該很清楚從[Javadoc中(HTTP://docs.spring。 IO /彈簧安全/網站/文檔/ 3.2.4.RELEASE/apidocs /組織/ springframework的/安全/配置/註解/網絡/ HttpSecurityBuilder.html)。 –
是的,過濾器被調用,但它發生「必須指定authenticationManager」。我不知道如何設置身份驗證管理器。我嘗試使用@Autowired認證管理器,但不起作用。 –