自定义认证过滤器:
UsernamePasswordAuthenticationFilter认证过滤器 此过滤器只接收form表单请求 且只过滤用户名和密码
我们可以仿造此类 自己构造认证过滤器
1)先继承AbstractAuthenticationProcessingFilter对象
2)构造方法中定义父类的有参构造方法 参数为过滤路径
3)重写attemptAuthentication方法
4)方法中先判断是否为ajax请求
5)如果是 就把请求通过jackson对象把输入流转换为map对象 并获取值
6)通过值 生成token
7)交给认证管理器认证token
此认证方法只获取了用户名和密码 顺便做了验证码的校对 通过验证之后再执行认证通过之后的方法
/*** @author by itheima* @Date 2022/1/21* @Description*/public class MyUserNamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {/*** 设置构造,传入自定义登录url地址* @param defaultFilterProcessesUrl*/public MyUserNamePasswordAuthenticationFilter(String defaultFilterProcessesUrl) {super(defaultFilterProcessesUrl);}@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {//从post请求流中获取登录信息String username=null;String password=null;try {//判断 是否是ajax登录if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)) {ServletInputStream in = request.getInputStream();HashMap<String,String> map = new ObjectMapper().readValue(in, HashMap.class);username=map.get("username");password=map.get("password");}} catch (IOException e) {e.printStackTrace();}//生成认证tokenUsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);//交给认证管理器取认证tokenreturn this.getAuthenticationManager().authenticate(token);}/*** 认证成功处理方法* @param request* @param response* @param chain* @param authResult* @throws IOException* @throws ServletException*/@Overrideprotected void successfulAuthentication(HttpServletRequest request,HttpServletResponse response,FilterChain chain,Authentication authResult) throws IOException, ServletException {response.getWriter().write("login success 666.....");}/*** 认证失败处理方法* @param request* @param response* @param failed* @throws IOException* @throws ServletException*/@Overrideprotected void unsuccessfulAuthentication(HttpServletRequest request,HttpServletResponse response,AuthenticationException failed) throws IOException, ServletException {response.getWriter().write("login failue 999");}}
在Security配置类中配置过滤器
1)把过滤器bean加入ioc容器 里面设置认证管理器
2)在configure方法中定义过滤器执行先后
/*** 配置授权策略* @param http* @throws Exception*/@Overrideprotected void configure(HttpSecurity http) throws Exception {http//坑-过滤器要添加在默认过滤器之前,否则,登录失效.addFilterBefore(myUserNamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class).csrf().disable();}@Beanpublic MyUserNamePasswordAuthenticationFilter myUserNamePasswordAuthenticationFilter() throws Exception {//设置默认登录路径MyUserNamePasswordAuthenticationFilter myUserNamePasswordAuthenticationFilter =new MyUserNamePasswordAuthenticationFilter("/authentication/form");//设置认证管理器 固定写法myUserNamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());return myUserNamePasswordAuthenticationFilter;}
