@Override protected void configure(HttpSecurity http) throws Exception { http .cors().and() .antMatcher("/**").authorizeRequests() .antMatchers("/", "/login**").permitAll() .anyRequest().authenticated() //这里必须要写formLogin(),不然原有的UsernamePasswordAuthenticationFilter不会出现,也就无法配置我们重新的UsernamePasswordAuthenticationFilter .and().formLogin().loginPage("/") .and().csrf().disable(); //用重写的Filter替换掉原有的UsernamePasswordAuthenticationFilter http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } //注册自定义的UsernamePasswordAuthenticationFilter @Bean CustomAuthenticationFilter customAuthenticationFilter() throws Exception { CustomAuthenticationFilter filter = new CustomAuthenticationFilter(); filter.setAuthenticationSuccessHandler(new SuccessHandler()); filter.setAuthenticationFailureHandler(new FailureHandler()); filter.setFilterProcessesUrl("/login/self"); //这句很关键,重用WebSecurityConfigurerAdapter配置的AuthenticationManager,不然要自己组装AuthenticationManager filter.setAuthenticationManager(authenticationManagerBean()); return filter; }
题外话,如果搭自己的oauth2的server,需要让spring security oauth2共享同一个AuthenticationManager(源码的解释是这样写可以暴露出这个AuthenticationManager,也就是注册到spring ioc)
@Override @Bean // share AuthenticationManager for web and oauth public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); }
至此,spring security就支持表单登录和异步json登录了。
参考来源
stackoverflow的问答
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU源码库。
注:相关教程知识阅读请移步到JAVA教程频道。