这个问题,网上找了好多,结果代码都不全,找了好多,要不是就自动注入的类注入不了,编译报错,要不异常捕获不了浪费好多时间,就觉得,框架不熟就不能随便用,全是坑,气死我了,最后改了两天.终于弄好啦;
问题主要是:
- 返回的验证码不知道在SpringSecurity的哪里和存在Session里的比较.
- 比较之后应该怎么处理,
- 其次是捕获验证码错误异常的处理,
这个问题比较多,网上大都是直接注入一个AuthenticationFailureHandler,我就不明白这个咋注进去的,我这个一写就报错,注入不进去,后来就想自己new一个哇,就OK了
new AuthenticationFailureHandler() { @Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { httpServletResponse.setContentType("application/json;charset=utf-8"); PrintWriter out = httpServletResponse.getWriter(); RespBean respBean = RespBean.error("验证码错误!"); out.write(new ObjectMapper().writeValueAsString(respBean)); out.flush(); out.close(); } }.onAuthenticationFailure(request, response, e); return;
流程
-
请求登录页,将验证码结果存到基于Servlet的session里,以JSON格式返回验证码,
-
之后前端发送登录请求,SpringSecurity中处理,自定义一个filter让它继承自OncePerRequestFilter,然后重写doFilterInternal方法,在这个方法中实现验证码的功能,如果验证码错误就抛出一个继承自AuthenticationException的验证吗错误的异常消息写入到响应消息中.
-
之后返回异常信息
下面以这个顺序书写代码:
依赖大家照着import导一下吧,记得有这两个,验证码需要一个依赖,之后还使用了一个工具包
<!--图片验证--> <dependency> <groupId>com.github.whvcse</groupId> <artifactId>easy-captcha</artifactId> <version>1.6.2</version> </dependency> <