登录页面提交
<div class="form-group">
<div class="pull-left">
<img alt="Code" onclick="this.src='/verify'" src="/verify" />
</div>
<div class="pull-right">
<input type="text" class="form-control" id="imgcode" name="imgcode" placeholder="Code">
</div>
</div>
图片验证码过滤器
/**
* 图片验证码过滤器。
* @author yanghaitao
*/
@Component
public class ImageCodeFilter extends OncePerRequestFilter {
/**
* 日志输出工具
*/
private final static Logger LOGGER = LoggerFactory.getLogger(ImageCodeFilter.class);
/**
* 只在登录时对验证码进行拦截,验证
*/
private static final String url = "/login";
/**
* redis缓存数据
*/
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 页面种植图片验证码cookie
*/
@Value("${server.servlet.session.cookie.imgname}")
private String imgCookieName;
/**
* 路径匹配工具
*/
private AntPathMatcher antPathMatcher = new AntPathMatcher();
/**
* 验证码拦截
*/
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
// 拦截登录请求
String requestURI = request.getRequestURI();
if(antPathMatcher.match(url, requestURI) && "POST".equals(request.getMethod())) {
// 获取种植的cookie
String cookieValue = IpUtils.getCookieValue(request, imgCookieName);
LOGGER.info("verify cookieValue : {}", cookieValue);
// 获取验证码
String imgcode = request.getParameter("imgcode");
LOGGER.info("verify imgcode : {}", imgcode);
// 获取redis缓存的验证码
String imgcodeRedis = redisTemplate.opsForValue().get(cookieValue);
try {
redisTemplate.delete(cookieValue);
} catch (Exception e) { }
LOGGER.info("verify imgcodeRedis : {}", imgcodeRedis);
// 验证码校验
if(imgcode == null || !imgcode.equalsIgnoreCase(imgcodeRedis)) {
response.sendRedirect("/login?error");
LOGGER.info("verify sendRedirect : {}", "/login?error");
return;
}
}
filterChain.doFilter(request, response);
}
}
配置验证码过滤器
注意:图片验证码请求要和静态资源一样放行,不然页面无法访问
@Autowired
private ImageCodeFilter imageCodeFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
LOGGER.info("SecurityConfig HttpSecurity ... ");
http.addFilterBefore(imageCodeFilter, UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/assets/**", "/verify").permitAll() // 放行地址与静态资源地址
.anyRequest().authenticated() // 其他地址军需验证
.and()
.formLogin()
.loginPage("/login")
.successHandler(new SuccessLoginHandler())
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
// .logoutSuccessHandler(new SuccessLogoutHandler())
.logoutSuccessUrl("/login?logout")
.permitAll()
.and().csrf().disable();
}