第一种方式,自定义AuthenticationProvider。这种方式在authenticate(Authentication authentication)方法中实现验证逻辑。supports方法返回true,才会执行authenticate方法。
实现完Provider后,需要在WebSecurityConfigurerAdapter中替换默认的AuthenticationProvider:
@Autowired private MyAuthProvider authProvider; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authProvider); }
第二种方式,自定义AbstractAuthenticationProcessingFilter。这种方式通过覆写attemptAuthentication方法来实现验证逻辑。自定义Filter后,需要在WebSecurityConfigurerAdapter添加该Filter:
@Bean public MyAuthFilter customUsernamePasswordAuthenticationFilter() throws Exception { MyAuthFilter customUsernamePasswordAuthenticationFilter = new MyAuthFilter(); customUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean()); customUsernamePasswordAuthenticationFilter .setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST")); return customUsernamePasswordAuthenticationFilter; } // @formatter:off @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(customUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); ... }
如果实际项目中,同时存在form登录和Restful方式的登录,可以两种方式结合使用或完全放在Filter中实现验证。在Filter中覆写obtainUsername、obtainPassword方法,解析JSON取得用户名、口令。然后再在Filter的attemptAuthentication方法或Provider中实现验证。
参考资料:http://blog.csdn.net/xiejx618/article/details/42609497
http://www.baeldung.com/spring-security-authentication-provider
https://blog.codecentric.de/en/2012/07/spring-security-two-security-realms-in-one-application/