五分钟带你玩转SpringSecurity(八)基操勿6

http.addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class) 将验证码过滤器链添加到用户过滤器之前。

@EnableWebSecurity

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

/**

  • 验证码过滤器

*/

@Autowired

private ImageCodeValidateFilter imageCodeValidateFilter;

@Override

protected void configure(HttpSecurity http) throws Exception {

// 验证码过滤器

http.addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class)

// 跳转前台的地址

.formLogin().loginPage(“/loginPage”)

// 登录调用的接口地址

.loginProcessingUrl(“/login”).successHandler(customAuthenticationSuccessHandler);

}

}

ImageCodeValidateFilter

验证码过滤器

@Component(“imageCodeValidateFilter”)

public class ImageCodeValidateFilter extends OncePerRequestFilter {

@Autowired

SecurityProperties securityProperties;

@Autowired

CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

@Override

protected void doFilterInternal(HttpServletRequest req 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 uest, HttpServletResponse response, FilterChain filterChain)

throws ServletException, IOException {

// 1. 如果是post方式 的登录请求,则校验输入的验证码是否正确

if (“/login”.equals(request.getRequestURI()) && request.getMethod().equalsIgnoreCase(“post”)) {

try {

// 校验验证码合法性

validate(request);

} catch (AuthenticationException e) {

// 交给失败处理器进行处理异常 也就是上文失败返回的json

customAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);

// 一定要记得结束

return;

}

}

// 放行请求 往下执行过滤器

filterChain.doFilter(request, response);

}

private void validate(HttpServletRequest request) {

// 先获取seesion中的验证码

String sessionCode = (String)request.getSession().getAttribute(CODE_SESSION_KEY);

// 获取用户输入的验证码

String inpuCode = request.getParameter(“code”);

// 判断是否正确

if (StringUtils.isBlank(inpuCode)) {

throw new ValidateCodeException(“验证码不能为空”);

}

if (!inpuCode.equalsIgnoreCase(sessionCode)) {

throw new ValidateCodeException(“验证码输入错误”);

}

}

}

CodeController

获取验证按接口

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值