前面五篇文章学习了最简单的一些登录认证流程,以及整个认证流程的源码走读,这篇文章就来看看如何实现图形验证码的登录。
开发生成验证码接口
获取验证码图片接口
- 根据随机数生成图片(生成验证码图片的代码网上很多,这里不再贴出)
- 将随机数存到Session中
- 将生成的图片写到接口的响应中
@GetMapping("/code/image")
public void createCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 生成图片
ImageCode imageCode = createCodeImageCode(request);
// 保存到session
sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
// 显示给前端
ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
}
- 该接口需要配置不被拦截
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form")
.successHandler(meicloudAuthenticationSuccessHandler)
.failureHandler(meicloudAuthenticationFailureHandler)
.and()
.authorizeRequests()
.antMatchers("/authentication/require",
securityProperties.getBrowser().getSignInPage(),
// 配置 “/code/image” 不被拦截
"/code/image").permitAll()
.anyRequest()
.authenticated()
.and()
.csrf().disable();
}
前端页面
- 前端需要传给后台
imageCode
,后台获取到后和Session
中保存的验证码进行验证。 - 页面代码:
<form action="/authentication/form" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>图形验证码:</td>
<td>
<input type="text" name="imageCode">
<img src="/code/image?width=200">
</td>
</tr>
<tr>
<td colspan="2"><button type="submit">登录</button></td>
</tr>
</table>
</form>
在认证流程中加入图形验证码校验
校验逻辑
- 首先后台需要自己定义一个过滤器来处理校验验证码的请求,验证通过之后继续调用后续过滤器
UserNamePasswordAuthenticationFilter
,如果验证不通过就抛异常返回错误信息。
public class ValidateCodeFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
ValidateCodeType type = getValidateCodeType(request);
if (type != null) {
logger.info("校验请求(" + request.getRequestURI() + ")中的验证码,验证码类型" + type);
try {
// 进行验证码的校验
validateCodeProcessorHolder.findValidateCodeProcessor(type)
.validate(new ServletWebRequest(request, response));
logger.info("验证码校验通过");
} catch (ValidateCodeException exception) {
// 如果校验抛出异常,则交给我们之前文章定义的异常处理器进行处理
authenticationFailureHandler.onAuthenticationFailure(request, response, exception);
return;
}
}
// 继续调用后边的过滤器
chain.doFilter(request, response);
}
}
- 校验的方法
@SuppressWarnings("unchecked")
@Override
public void validate(ServletWebRequest request) {
// 获取session中的imageCode
ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request, ValidateCodeController.SESSION_KEY);
String codeInRequest;
try {
// 获取前端传过来的imageCode
codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),
"imageCode");
} catch (ServletRequestBindingException e) {
throw new ValidateCodeException("获取验证码的值失败");
}
if (StringUtils.isBlank(codeInRequest)) {
throw new ValidateCodeException(codeType + "验证码的值不能为空");
}
if (codeInSession == null) {
throw new ValidateCodeException(codeType + "验证码不存在");
}
if (codeInSession.isExpried()) {
validateCodeRepository.remove(request, codeType);
throw new ValidateCodeException(codeType + "验证码已过期");
}
if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
throw new ValidateCodeException(codeType + "验证码不匹配");
}
// 校验完之后记得将其移除
sessionStrategy.removeAttribute(request, ValidateCodeController.SESSION_KEY);
}
- 将自己定义的校验验证码的过滤器加到
UserNamePasswordAuthenticationFilter
之前
@Override
protected void configure(HttpSecurity http) throws Exception {
// 验证码校验过滤器
ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
// 将验证码校验过滤器加到 UsernamePasswordAuthenticationFilter 过滤器之前
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin()
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form")
.successHandler(meicloudAuthenticationSuccessHandler)
.failureHandler(meicloudAuthenticationFailureHandler)
.and()
.authorizeRequests()
.antMatchers("/authentication/require",
securityProperties.getBrowser().getSignInPage(),
"/code/image").permitAll()
.anyRequest()
.authenticated()
.and()
.csrf().disable();
}