springboot springsecurity实现图片验证码登录的示例-亚博电竞手机版

这个问题,网上找了好多,结果代码都不全,找了好多,要不是就自动注入的类注入不了,编译报错,要不异常捕获不了浪费好多时间,就觉得,框架不熟就不能随便用,全是坑,气死我了,最后改了两天.终于弄好啦;

问题主要是:

  • 返回的验证码不知道在springsecurity的什么地方和存在内存里的比较?我用的方法是前置一个过滤器,插入到表单验证之前。
  • 比较之后应该怎么处理,:比较之后要抛出一个继承了authenticationexception的异常
  • 其次是捕获验证码错误异常的处理? 捕获到的异常交给自定义验证失败处理器authenticationfailurehandler处理,这里,用的处理器要和表单验证失败的处理器是同一个处理器,不然会报异常,所以在需要写一个全局的authenticationfailurehandler的实现类,专门用来处理异常。表单验证有成功和失败两个处理器,我们一般直接以匿名内部类形似写。要是加了验证码,就必须使用统一的失败处理器。

效果图

网上大都是直接注入一个authenticationfailurehandler,我当时就不明白这个咋注进去的,我这个一写就报错,注入不进去,后来就想自己new一个哇,可以是可以了,但是还报异常,java.lang.illegalstateexception: cannot call senderror() after the response has been committed,后来想表单验证的时候,失败用的也是这个处理器,就想定义一个全局的处理器,

package com.liruilong.hros.config; import com.fasterxml.jackson.databind.objectmapper; import com.liruilong.hros.exception.validatecodeexception; import com.liruilong.hros.model.respbean; import org.springframework.context.annotation.bean; import org.springframework.security.authentication.*; import org.springframework.security.core.authenticationexception; import org.springframework.security.web.authentication.authenticationfailurehandler; import org.springframework.stereotype.component; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; import java.io.printwriter; /** * @description : * @author: liruilong * @date: 2020/2/11 23:08 */ @component public class myauthenticationfailurehandler implements 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(e.getmessage()); // 验证码自定义异常的处理 if (e instanceof validatecodeexception){ respbean.setmsg(e.getmessage()); //security内置的异常处理 }else if (e instanceof lockedexception) { respbean.setmsg("账户被锁定请联系管理员!"); } else if (e instanceof credentialsexpiredexception) { respbean.setmsg("密码过期请联系管理员!"); } else if (e instanceof accountexpiredexception) { respbean.setmsg("账户过期请联系管理员!"); } else if (e instanceof disabledexception) { respbean.setmsg("账户被禁用请联系管理员!"); } else if (e instanceof badcredentialsexception) { respbean.setmsg(http://www.cppcns.com"用户名密码输入错误,请重新输入!"); } //将hr转化为sting out.write(new objectmapper().writevalueasstring(respbean)); out.flush(); out.close(); } @bean public myauthenticationfailurehandler getmyauthenticationfailurehandler(){ return new myauthenticationfailurehandler(); } }

流程

  1. 请求登录页,将验证码结果存到基于servlet的session里,以json格式返回验证码,
  2. 之后前端发送登录请求,springsecurity中处理,自定义一个filter让它继承自onceperrequestfilter,然后重写dofilterinternal方法,在这个方法中实现验证码验证的功能,如果验证码错误就抛出一个继承自authenticationexception的验证吗错误的异常消息写入到响应消息中.
  3. 之后返回异常信息交给自定义验证失败处理器处理。

下面以这个顺序书写代码:

依赖大家照着import导一下吧,记得有这两个,验证码需要一个依赖,之后还使用了一个工具依赖包,之后是前端代码

com.github.whvcse easy-captcha 1.6.2 org.apache.commons commons-lang3

后端代码:

获取验证码,将结果放到session里

package com.liruilong.hros.controller; import com.liruilong.hros.model.respbean; import org.springframework.web.bind.annotation.getmapping; import org.springframework.web.bind.annotation.restcontroller; import com.wf.captcha.arithmeticcaptcha; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.util.hashmap; import java.util.map; /** * @description : * @author: liruilong * @date: 2019/12/19 19:58 */ @restcontroller public class logincontroller { @getmapping(value = "/auth/code") public map getcode(httpservletrequest request,httpservletresponse response){ // 算术类型 https://gitee.com/whvse/easycaptcha arithmeticcaptcha captcha = new arithmeticcaptcha(111, 36); // 几位数运算,默认是两位 captcha.setlen(2); // 获取运算的结果 string result = captcha.text(); system.err.println("生成的验证码:" result)www.cppcns.com; // 保存 // 验证码信息 map imgresult = new hashmap(2){{ put("img", captcha.tobase64()); }}; request.getsession().setattribute("yanzhengma",result); return imgresult; } }

定义一个verifycodefilter过滤器

package com.liruilong.hros.filter; import com.liruilong.hros.exception.validatecodeexception; import com.liruilong.hros.config.myauthenticationfailurehandler; import org.apache.commons.lang3.stringutils; import org.springframework.beans.factory.annotation.autowired; import org.springframework.context.annotation.bean; import org.springframework.security.core.authenticationexception; import org.springframework.stereotype.component; import org.springframework.web.filter.onceperrequestfilter; import javax.servlet.filterchain; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; /** * @description : * @author: liruilong * @date: 2020/2/7 19:39 */ @component public class verifycodefilter extends onceperrequestfilter { @bean public verifycodefilter getverifycodefilter() { return new verifycodefilter(); } @autowired myauthenticationfailurehandler myauthenticationfailurehandler; @override protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain filterchain) throws servletexception, ioexception { if (stringutils.equals("/dologin", request.getrequesturi()) && stringutils.equalsignorecase(request.getmethod(), "post")) { // 1. 进行验证码的校验 try { string requestcaptcha = request.getparameter("code"); if (requestcaptcha == null) { throw new validatecodeexception("验证码不存在"); } string code = (string) request.getsession().getattribute("yanzhengma"); if (stringutils.isblank(code)) { throw new validatecodeexception("验证码过期!"); } code = code.equals("0.0") ? "0" : code; logger.info("开始校验验证码,生成的验证码为:" code " ,输入的验证码为:" requestcaptcha); if (!stringutils.equals(code, requestcaptcha)) { throw new validatecodeexception("验证码不匹配"); } } catch (authenticationexception e) { // 2. 捕获步骤1中校验出现异常,交给失败处理类进行进行处理 myauthenticationfailurehandler.onauthenticationfailure(request, response, e); } finally { filterchain.dofilter(request, response); } } else { filterchain.dofilter(request, response); } } }

定义一个自定义异常处理,继承authenticationexception

package com.liruilong.hros.exception; import org.springframework.security.core.authenticationexception; /** * @description : * @author: liruilong * @date: 2020/2/8 7:24 */ public class validatecodeexception extends authenticationexception { public validatecodeexception(string msg) { super(msg); } }

security配置.

在之前的基础上加filter的基础上加了

http.addfilterbefore(verifycodefilter, usernamepasswordauthenticationfilter.class),验证处理上,验证码和表单验证失败用同一个失败处理器,

package com.liruilong.hros.config; import com.fasterxml.jackson.databind.objectmapper; import com.liruilong.hros.filter.verifycodefilter; import com.liruilong.hros.model.hr; import com.liruilong.hros.model.respbean; import com.liruilong.hros.service.hrservice; import org.springframework.beans.factory.annotation.autowired; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.security.authentication.*; import org.springframework.security.config.annotation.objectpostprocessor; import org.springframework.security.config.annotation.authentication.builders.authenticationmanagerbuilder; import org.springframework.security.config.annotation.web.builders.httpsecurity; import org.springframework.security.config.annotation.web.builders.websecurity; import org.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter; import org.springframework.security.core.authentication; import org.springframework.security.core.authenticationexception; import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder; import org.springframework.security.crypto.password.passwordencoder; import org.springframework.security.web.authenticationentrypoint; import org.springframework.security.web.access.intercept.filtersecurityinterceptor; import org.springframework.security.web.authentication.authenticationsuccesshandler; import org.springframework.security.web.authentication.usernamepasswordauthenticationfilter; import org.springframework.security.web.authentication.logout.logoutsuccesshandler; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; import java.io.printwriter; /** * @description : * @author: liruilong * @date: 2019/12/18 19:11 */ @configuration public class securityconfig extends websecurityconfigureradapter { @autowired hrservice hrservice; @autowired customfilterinvocationsecuritymetadatasource customfilterinvocationsecuritymetadatasource; @autowired customurldecisionmanager customurldecisionmanager; @autowired verifycodefilter verifycodefilter ; @autowired myauthenticationfailurehandler myauthenticationfailurehandler; @bean passwordencoder passwordencoder() { return new bcryptpasswordencoder(); } @override protected void configure(authenticationmanagerbuilder auth) throws exception { auth.userdetailsservice(hrservice); } /** * @author liruilong * @description 放行的请求路径 * @date 19:25 2020/2/7 * @param [web] * @return void **/ @override public void configure(websecurity web) throws exception { web.ignoring().antmatchers("/auth/code","/login","/css/**","/js/**", "/index.html", "/img/**", "/fonts/**","/favicon.ico"); } @override protected void configure(httpsecurity http) throws exception { http .addfilterbefore(verifycodefilter, usernamepasswordauthenticationfilter.class) .authorizerequests() //.anyrequest().authenticated() .withobjectpostprocessor(new objectpostprocessor() { @override public o postprocess(o object) { object.setaccessdecisionmanager(customurldecisionmanager); object.setsecuritymetadatasource(customfilterinvocationsecuritymetadatasource); return object; } }) .and().formlogin().usernameparameter("username").passwordparameter("password") .loginprocessing .loginpage("/login") //登录成功回调 .successhandler(new authenticationsuccesshandler() { @override public void onauthenticationsuccess(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, authentication authentication) throws ioexception, servletexception { httpservletresponse.setcontenttype("application/json;charset=utf-8"); printwriter out = httpservletresponse.getwriter(); hr hr = (hr) authentication.getprincipal(); //密码不回传 hr.setpassword(null); respbean ok = respbean.ok("登录成功!", hr); //将hr转化为sting string s = new objectmapper().writevalueasstring(ok); out.write(s); out.flush(); out.close(); } }) //登失败回调 .failurehandler(myauthenticationfailurehandler) //相关的接口直接返回 .permitall() .and() .logout() //注销登录 // .logoutsuccess .logoutsuccesshandler(new logoutsuccesshandler() { @override public void onlogoutsuccess(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, authentication authentication) throws ioexception, servletexception { httpservletresponse.setcontenttype("application/json;charset=utf-8"); printwriter out = httpservletresponse.getwriter(); out.write(new objectmapper().writevalueasstring(respbean.ok("注销成功!"))); out.flush(); out.close(); } }) .permhttp://www.cppcns.comitall() .and() .csrf().disable().exceptionhandling() //没有认证时,在这里处理结果,不要重定向 .authenticationentrypoint(new authenticationentrypoint() { @override public void commence(httpservletrequest req, httpservletresponse resp, authenticationexception authexception) throws ioexception, servletexception { resp.setcontenttype("application/json;charset=utf-8"); resp.setstatus(401); printwriter out = resp.getwriter(); respbean respbean = respbean.error("访问失败!"); if (authexception instanceof insufficientauthenticationexception) { respbean.setmsg("请求失败,请联系管理员!"); } out.write(new objectmapper().writevalueasstring(respbean)); out.flush(); out.close(); } }); } }

到此这篇关于springboot springsecurity实现图片验证码登录的示例的文章就介绍到这了,更多相关springboot springsecurity图片验证码登录内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

展开全文
内容来源于互联网和用户投稿,文章中一旦含有亚博电竞手机版的联系方式务必识别真假,本站仅做信息展示不承担任何相关责任,如有侵权或涉及法律问题请联系亚博电竞手机版删除

最新文章

网站地图