The function of spring-security is mainly implemented by a bunch of filters to form a filter chain, and each filter will do its part. What I'm going to do today is to extend the Usernamepasswordauthenticationfilter, add a filter, and complete the verification of the check code on the login page. Here is a description of the filter, followed by a custom login verification filter.
https://docs.spring.io/spring-security/site/docs/3.2.8.RELEASE/reference/htmlsingle/#ns-web-advanced
First, the extension abstractauthenticationprocessingfilter, realizes the Myusernamepasswordauthenticationfilter.
PackageSimm.spring.web.config;Importjava.io.IOException;ImportJavax.servlet.FilterChain;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession;Importorg.springframework.security.authentication.InsufficientAuthenticationException;Importorg.springframework.security.core.Authentication;ImportOrg.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;ImportOrg.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;ImportOrg.springframework.security.web.util.matcher.AntPathRequestMatcher;Importorg.springframework.util.StringUtils; Public classMyusernamepasswordauthenticationfilterextendsAbstractauthenticationprocessingfilter {//whether to turn on the verification code function Private BooleanIsopenvalidatecode =true; Public Static FinalString Validate_code = "Validatecode"; PublicMyusernamepasswordauthenticationfilter () {Super(NewAntpathrequestmatcher ("/user/login.do", "POST")); Simpleurlauthenticationfailurehandler Failedhandler=(Simpleurlauthenticationfailurehandler) Getfailurehandler (); Failedhandler.setdefaultfailureurl ("/user/login.do?validerror"); } @Override Public voidDoFilter (ServletRequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {httpservletrequest req=(httpservletrequest) request; HttpServletResponse Res=(httpservletresponse) response; if(!requiresauthentication (req, res)) {Chain.dofilter (request, response); return; } if(isopenvalidatecode) {if(!checkvalidatecode (req, res))return; } //Save some session informationHttpSession session =req.getsession (); Session.setattribute (Validate_code,"MyTest"); Chain.dofilter (Request,response); } /*** Override the authorization verification method, where you can do some of the session settings you need*/ PublicAuthentication Attemptauthentication (HttpServletRequest request, httpservletresponse response)throwsIOException, servletexception {return NULL; } protected BooleanCheckvalidatecode (httpservletrequest request,httpservletresponse response)throwsIOException, servletexception {HttpSession session=request.getsession (); String Sessionvalidatecode=Obtainsessionvalidatecode (session); Sessionvalidatecode= "1234";//make a fake verification code;//to invalidate the last verification codeSession.setattribute (Validate_code,NULL); String Validatecodeparameter=Obtainvalidatecodeparameter (Request); if(Stringutils.isempty (validatecodeparameter) | |!sessionvalidatecode.equalsignorecase (Validatecodeparameter)) {unsuccessfulauthentication (Request, Response,NewInsufficientauthenticationexception ("Incorrect verification code entered")); return false; } return true; } PrivateString Obtainvalidatecodeparameter (httpservletrequest request) {Object obj=Request.getparameter (Validate_code); return NULL= = obj? "": Obj.tostring (); } protectedString Obtainsessionvalidatecode (HttpSession session) {Object obj=Session.getattribute (Validate_code); return NULL= = obj? "": Obj.tostring (); }}
Code interpretation
1. Specify the request address filter for filter to intercept the login request. Call the Abstractauthenticationprocessingfilter.requiresauthentication method.
2. Specify a jump page for verification failure
3. Test code of verification code. False verification code 1234, compared to the page parameters, if not equal throws an "incorrect input code" exception.
4, verification through, continue to carry out the subsequent filter chain. Otherwise, exit the request processing logic. This filter only handles the verification logic of the validation code, and the authentication of the user name password is given to the following usernamepasswordauthenticationfilter to handle.
Insert a custom filter into the Httpsecurity filter chain and insert it into the usernamepasswordauthenticationfilter position. The insertion method has addfilterbefore,addfilterat,addfilterafter. This place needs to note that the use of Addfilterat is not to replace the original filter, in fact, the framework of the original filter in the process of starting the Httpsecurity configuration, the framework has completed a certain degree of fixed configuration, is not allowed to change the replacement. Depending on the test results, the filter inserted by the call to the Addfilterat method is executed before the original filter in this position.
@Override protected void throws Exception { = "/**/*.do"; HTTP . Addfilterat (new myusernamepasswordauthenticationfilter (), Usernamepasswordauthenticationfilter. class)
Third, the login method to add to the verification code error callback interception
@Controller @requestmapping ("/USER") Public classUsercontroller {@RequestMapping (value= "/login", method =requestmethod.get) PublicString Login (@RequestParam (value = "error", required =false) String error, @RequestParam (value = "Validerror", required = false ) String validerror, @RequestParam (value= "Logout", required =false) String Logout,model Model) {if(Error! =NULL) {Model.addattribute ("MSG", "User name or password error!" "); } if(validerror!=null) {Model.addattribute ("msg", "CAPTCHA Error! "); } if(Logout! =NULL) {Model.addattribute ("MSG", "Successful exit!" "); } return"User/login"; }
Iv. Display of test results
The above is my custom filter implementation for the login feature. The other filter is the same and can be expanded if necessary. Not many things, I hope you have some help, welcome message exchange.
Spring-security Custom Filter Completion verification code check