springboot springsecurity怎么实现图片验证码登录-mile米乐体育

springboot springsecurity怎么实现图片验证码登录

本文小编为大家详细介绍“springboot springsecurity怎么实现图片验证码登录”,内容详细,步骤清晰,细节处理妥当,希望这篇“springboot springsecurity怎么实现图片验证码登录”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

效果图

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

packagecom.liruilong.hros.config;importcom.fasterxml.jackson.databind.objectmapper;importcom.liruilong.hros.exception.validatecodeexception;importcom.liruilong.hros.model.respbean;importorg.springframework.context.annotation.bean;importorg.springframework.security.authentication.*;importorg.springframework.security.core.authenticationexception;importorg.springframework.security.web.authentication.authenticationfailurehandler;importorg.springframework.stereotype.component;importjavax.servlet.servletexception;importjavax.servlet.http.httpservletrequest;importjavax.servlet.http.httpservletresponse;importjava.io.ioexception;importjava.io.printwriter;/***@description:*@author:liruilong*@date:2020/2/1123:08*/@componentpublicclassmyauthenticationfailurehandlerimplementsauthenticationfailurehandler{@overridepublicvoidonauthenticationfailure(httpservletrequesthttpservletrequest,httpservletresponsehttpservletresponse,authenticationexceptione)throwsioexception,servletexception{httpservletresponse.setcontenttype("application/json;charset=utf-8");printwriterout=httpservletresponse.getwriter();respbeanrespbean=respbean.error(e.getmessage());//验证码自定义异常的处理if(einstanceofvalidatecodeexception){respbean.setmsg(e.getmessage());//security内置的异常处理}elseif(einstanceoflockedexception){respbean.setmsg("账户被锁定请联系管理员!");}elseif(einstanceofcredentialsexpiredexception){respbean.setmsg("密码过期请联系管理员!");}elseif(einstanceofaccountexpiredexception){respbean.setmsg("账户过期请联系管理员!");}elseif(einstanceofdisabledexception){respbean.setmsg("账户被禁用请联系管理员!");}elseif(einstanceofbadcredentialsexception){respbean.setmsg("用户名密码输入错误,请重新输入!");}//将hr转化为stingout.write(newobjectmapper().writevalueasstring(respbean));out.flush();out.close();}@beanpublicmyauthenticationfailurehandlergetmyauthenticationfailurehandler(){returnnewmyauthenticationfailurehandler();}}

流程

  1. 请求登录页,将验证码结果存到基于servlet的session里,以json格式返回验证码,

  2. 之后前端发送登录请求,springsecurity中处理,自定义一个filter让它继承自onceperrequestfilter,然后重写dofilterinternal方法,在这个方法中实现验证码验证的功能,如果验证码错误就抛出一个继承自authenticationexception的验证吗错误的异常消息写入到响应消息中.

  3. 之后返回异常信息交给自定义验证失败处理器处理。

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

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

com.github.whvcseeasy-captcha1.6.2org.apache.commonscommons-lang3

后端代码:

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

packagecom.liruilong.hros.controller;importcom.liruilong.hros.model.respbean;importorg.springframework.web.bind.annotation.getmapping;importorg.springframework.web.bind.annotation.restcontroller;importcom.wf.captcha.arithmeticcaptcha;importjavax.servlet.http.httpservletrequest;importjavax.servlet.http.httpservletresponse;importjava.util.hashmap;importjava.util.map;/***@description:*@author:liruilong*@date:2019/12/1919:58*/@restcontrollerpublicclasslogincontroller{@getmapping(value="/auth/code")publicmapgetcode(httpservletrequestrequest,httpservletresponseresponse){//算术类型https://gitee.com/whvse/easycaptchaarithmeticcaptchacaptcha=newarithmeticcaptcha(111,36);//几位数运算,默认是两位captcha.setlen(2);//获取运算的结果stringresult=captcha.text();system.err.println("生成的验证码:" result);//保存//验证码信息mapimgresult=newhashmap(2){{put("img",captcha.tobase64());}};request.getsession().setattribute("yanzhengma",result);returnimgresult;}}

定义一个verifycodefilter过滤器

packagecom.liruilong.hros.filter;importcom.liruilong.hros.exception.validatecodeexception;importcom.liruilong.hros.config.myauthenticationfailurehandler;importorg.apache.commons.lang3.stringutils;importorg.springframework.beans.factory.annotation.autowired;importorg.springframework.context.annotation.bean;importorg.springframework.security.core.authenticationexception;importorg.springframework.stereotype.component;importorg.springframework.web.filter.onceperrequestfilter;importjavax.servlet.filterchain;importjavax.servlet.servletexception;importjavax.servlet.http.httpservletrequest;importjavax.servlet.http.httpservletresponse;importjava.io.ioexception;/***@description:*@author:liruilong*@date:2020/2/719:39*/@componentpublicclassverifycodefilterextendsonceperrequestfilter{@beanpublicverifycodefiltergetverifycodefilter(){returnnewverifycodefilter();}@autowiredmyauthenticationfailurehandlermyauthenticationfailurehandler;@overrideprotectedvoiddofilterinternal(httpservletrequestrequest,httpservletresponseresponse,filterchainfilterchain)throwsservletexception,ioexception{if(stringutils.equals("/dologin",request.getrequesturi())&&stringutils.equalsignorecase(request.getmethod(),"post")){//1.进行验证码的校验try{stringrequestcaptcha=request.getparameter("code");if(requestcaptcha==null){thrownewvalidatecodeexception("验证码不存在");}stringcode=(string)request.getsession().getattribute("yanzhengma");if(stringutils.isblank(code)){thrownewvalidatecodeexception("验证码过期!");}code=code.equals("0.0")?"0":code;logger.info("开始校验验证码,生成的验证码为:" code ",输入的验证码为:" requestcaptcha);if(!stringutils.equals(code,requestcaptcha)){thrownewvalidatecodeexception("验证码不匹配");}}catch(authenticationexceptione){//2.捕获步骤1中校验出现异常,交给失败处理类进行进行处理myauthenticationfailurehandler.onauthenticationfailure(request,response,e);}finally{filterchain.dofilter(request,response);}}else{filterchain.dofilter(request,response);}}}

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

packagecom.liruilong.hros.exception;importorg.springframework.security.core.authenticationexception;/***@description:*@author:liruilong*@date:2020/2/87:24*/publicclassvalidatecodeexceptionextendsauthenticationexception{publicvalidatecodeexception(stringmsg){super(msg);}}

security配置.

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

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

packagecom.liruilong.hros.config;importcom.fasterxml.jackson.databind.objectmapper;importcom.liruilong.hros.filter.verifycodefilter;importcom.liruilong.hros.model.hr;importcom.liruilong.hros.model.respbean;importcom.liruilong.hros.service.hrservice;importorg.springframework.beans.factory.annotation.autowired;importorg.springframework.context.annotation.bean;importorg.springframework.context.annotation.configuration;importorg.springframework.security.authentication.*;importorg.springframework.security.config.annotation.objectpostprocessor;importorg.springframework.security.config.annotation.authentication.builders.authenticationmanagerbuilder;importorg.springframework.security.config.annotation.web.builders.httpsecurity;importorg.springframework.security.config.annotation.web.builders.websecurity;importorg.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter;importorg.springframework.security.core.authentication;importorg.springframework.security.core.authenticationexception;importorg.springframework.security.crypto.bcrypt.bcryptpasswordencoder;importorg.springframework.security.crypto.password.passwordencoder;importorg.springframework.security.web.authenticationentrypoint;importorg.springframework.security.web.access.intercept.filtersecurityinterceptor;importorg.springframework.security.web.authentication.authenticationsuccesshandler;importorg.springframework.security.web.authentication.usernamepasswordauthenticationfilter;importorg.springframework.security.web.authentication.logout.logoutsuccesshandler;importjavax.servlet.servletexception;importjavax.servlet.http.httpservletrequest;importjavax.servlet.http.httpservletresponse;importjava.io.ioexception;importjava.io.printwriter;/***@description:*@author:liruilong*@date:2019/12/1819:11*/@configurationpublicclasssecurityconfigextendswebsecurityconfigureradapter{@autowiredhrservicehrservice;@autowiredcustomfilterinvocationsecuritymetadatasourcecustomfilterinvocationsecuritymetadatasource;@autowiredcustomurldecisionmanagercustomurldecisionmanager;@autowiredverifycodefilterverifycodefilter;@autowiredmyauthenticationfailurehandlermyauthenticationfailurehandler;@beanpasswordencoderpasswordencoder(){returnnewbcryptpasswordencoder();}@overrideprotectedvoidconfigure(authenticationmanagerbuilderauth)throwsexception{auth.userdetailsservice(hrservice);}/***@authorliruilong*@description放行的请求路径*@date19:252020/2/7*@param[web]*@returnvoid**/@overridepublicvoidconfigure(websecurityweb)throwsexception{web.ignoring().antmatchers("/auth/code","/login","/css/**","/js/**","/index.html","/img/**","/fonts/**","/favicon.ico");}@overrideprotectedvoidconfigure(httpsecurityhttp)throwsexception{http.addfilterbefore(verifycodefilter,usernamepasswordauthenticationfilter.class).authorizerequests()//.anyrequest().authenticated().withobjectpostprocessor(newobjectpostprocessor(){@overridepublicopostprocess(oobject){object.setaccessdecisionmanager(customurldecisionmanager);object.setsecuritymetadatasource(customfilterinvocationsecuritymetadatasource);returnobject;}}).and().formlogin().usernameparameter("username").passwordparameter("password").loginprocessing.loginpage("/login")//登录成功回调.successhandler(newauthenticationsuccesshandler(){@overridepublicvoidonauthenticationsuccess(httpservletrequesthttpservletrequest,httpservletresponsehttpservletresponse,authenticationauthentication)throwsioexception,servletexception{httpservletresponse.setcontenttype("application/json;charset=utf-8");printwriterout=httpservletresponse.getwriter();hrhr=(hr)authentication.getprincipal();//密码不回传hr.setpassword(null);respbeanok=respbean.ok("登录成功!",hr);//将hr转化为stingstrings=newobjectmapper().writevalueasstring(ok);out.write(s);out.flush();out.close();}})//登失败回调.failurehandler(myauthenticationfailurehandler)//相关的接口直接返回.permitall().and().logout()//注销登录//.logoutsuccess.logoutsuccesshandler(newlogoutsuccesshandler(){@overridepublicvoidonlogoutsuccess(httpservletrequesthttpservletrequest,httpservletresponsehttpservletresponse,authenticationauthentication)throwsioexception,servletexception{httpservletresponse.setcontenttype("application/json;charset=utf-8");printwriterout=httpservletresponse.getwriter();out.write(newobjectmapper().writevalueasstring(respbean.ok("注销成功!")));out.flush();out.close();}}).permitall().and().csrf().disable().exceptionhandling()//没有认证时,在这里处理结果,不要重定向.authenticationentrypoint(newauthenticationentrypoint(){@overridepublicvoidcommence(httpservletrequestreq,httpservletresponseresp,authenticationexceptionauthexception)throwsioexception,servletexception{resp.setcontenttype("application/json;charset=utf-8");resp.setstatus(401);printwriterout=resp.getwriter();respbeanrespbean=respbean.error("访问失败!");if(authexceptioninstanceofinsufficientauthenticationexception){respbean.setmsg("请求失败,请联系管理员!");}out.write(newobjectmapper().writevalueasstring(respbean));out.flush();out.close();}});}}

读到这里,这篇“springboot springsecurity怎么实现图片验证码登录”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注恰卡编程网行业资讯频道。

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

最新文章

网站地图