⒈ Encapsulating captcha classes

 package cn.coreqi.security.validate;
import java.awt.image.BufferedImage;
import java.time.LocalDateTime; public class ImageCode {
private BufferedImage image;
private String code;
private LocalDateTime expireTime; // Expiration time public ImageCode(BufferedImage image, String code, Integer expireIn) {
this.image = image;
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
} public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {
this.image = image;
this.code = code;
this.expireTime = expireTime;
} public boolean isExpried(){
return LocalDateTime.now().isAfter(expireTime);
} public BufferedImage getImage() {
return image;
} public void setImage(BufferedImage image) {
this.image = image;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code;
} public LocalDateTime getExpireTime() {
return expireTime;
} public void setExpireTime(LocalDateTime expireTime) {
this.expireTime = expireTime;
}
}

⒉ Package captcha controller

 package cn.coreqi.security.controller;
import cn.coreqi.security.validate.ImageCode;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest; import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random; @RestController
public class ValidateController { public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy(); @GetMapping("code/image")
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
ImageCode imageCode = createImageCode(request);
sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,imageCode); response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
//response.setDateHeader("Expires", 0); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
encoder.encode(imageCode.getImage()); //ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream()); // When tomcat Next temp If the folder does not exist "Can't create output stream"
} private ImageCode createImageCode(HttpServletRequest request) {
int width = 67;
int height = 23;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(getRandColor(200,250));
g.fillRect(0,0,width,height);
g.setFont(new Font("Times New Roman",Font.ITALIC,20));
g.setColor(getRandColor(160,200));
for (int i = 0;i < 155; i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x,y,x+xl,y+yl);
}
String sRand = "";
for(int i = 0;i < 4; i++){
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110),20 + random.nextInt(110),20 + random.nextInt(110)));
g.drawString(rand,13 * i + 6,16);
}
g.dispose();
return new ImageCode(image,sRand,60);
} /**
* Generate random background stripes
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if(fc > 255){
fc = 255;
}
if(bc > 255){
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r,g,b);
}
}

⒊ Release verification code Rest Address

⒋ Add verification code to the form

 <tr>
<td> Graphic verification code :</td>
<td>
<input type="text" name="imageCode">
<img src="/code/image">
</td>
</tr>

⒌ Declare a captcha exception , Used to throw specific captcha exceptions

 package cn.coreqi.security.validate;
import org.springframework.security.core.AuthenticationException;
public class ValidateCodeException extends AuthenticationException {
public ValidateCodeException(String msg) {
super(msg);
}
}

⒍ Create a filter , Used to verify that the captcha in the request is correct

 package cn.coreqi.security.Filter;
import cn.coreqi.security.validate.ImageCode;
import cn.coreqi.security.validate.ValidateCodeException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import cn.coreqi.security.controller.*; import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class ValidateCodeFilter extends OncePerRequestFilter { private AuthenticationFailureHandler authenticationFailureHandler; private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy(); public AuthenticationFailureHandler getAuthenticationFailureHandler() {
return authenticationFailureHandler;
} public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
this.authenticationFailureHandler = authenticationFailureHandler;
} public SessionStrategy getSessionStrategy() {
return sessionStrategy;
} public void setSessionStrategy(SessionStrategy sessionStrategy) {
this.sessionStrategy = sessionStrategy;
} @Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
if (httpServletRequest.equals("/authentication/form") && httpServletRequest.getMethod().equals("post")) {
try {
validate(new ServletWebRequest(httpServletRequest)); }catch (ValidateCodeException e){
authenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
return;
}
}
filterChain.doFilter(httpServletRequest,httpServletResponse); // If it's not a login request , Directly call the following filter chain
} private void validate(ServletWebRequest request) throws ServletRequestBindingException {
ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request,ValidateController.SESSION_KEY);
String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),"imageCode");
if(!StringUtils.hasText(codeInRequest)){
throw new ValidateCodeException(" The value of the verification code cannot be empty !");
}
if(codeInSession == null){
throw new ValidateCodeException(" Verification code does not exist !");
}
if(codeInSession.isExpried()){
sessionStrategy.removeAttribute(request,ValidateController.SESSION_KEY);
throw new ValidateCodeException(" The verification code has expired !");
}
if(!codeInSession.getCode().equals(codeInRequest)){
throw new ValidateCodeException(" The verification code is incorrect !");
}
sessionStrategy.removeAttribute(request,ValidateController.SESSION_KEY);
}
}

⒎ stay SpringSecurity Register our filters in the filter chain

 package cn.coreqi.security.config;
import cn.coreqi.security.Filter.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private AuthenticationSuccessHandler coreqiAuthenticationSuccessHandler; @Autowired
private AuthenticationFailureHandler coreqiAuthenticationFailureHandler; @Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
} @Override
protected void configure(HttpSecurity http) throws Exception {
ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
validateCodeFilter.setAuthenticationFailureHandler(coreqiAuthenticationFailureHandler); //http.httpBasic() //httpBasic Sign in BasicAuthenticationFilter
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // Before loading the user name password filter
.formLogin() // Form login UsernamePasswordAuthenticationFilter
.loginPage("/coreqi-signIn.html") // Specify login page
//.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") // Specify the address of the form submission to replace UsernamePasswordAuthenticationFilter Default submission address
.successHandler(coreqiAuthenticationSuccessHandler) // After successful login, we need to use our custom login success processor , no need Spring default .
.failureHandler(coreqiAuthenticationFailureHandler) // I feel that
.and()
.authorizeRequests() // Configure authorization requests
.antMatchers("/coreqi-signIn.html","/code/image").permitAll() // Specify that the login page does not require authentication
.anyRequest().authenticated() // Any request requires authentication
.and().csrf().disable(); // Ban CSRF
//FilterSecurityInterceptor Whole SpringSecurity The last link in the filter chain
}
}

SpringSecurity Realize the function of graphic captcha more related articles

  1. SpringSceurity(3)--- Graphic verification code function implementation

    SpringSceurity(3)--- Graphic verification code function implementation of springSceurity I've written two articles before : 1.SpringSecurity(1)--- authentication + Authorization code implements 2.SpringSec ...

  2. Tornado The framework realizes the function of graphic captcha

    Graphic captcha is a function often encountered in the process of project development , In many languages, there are different forms of encapsulation of captcha functions ,python There are similar encapsulation operations in , Generate a specified graphic data by drawing , Let the front end HTML The page is linked to ...

  3. spring boot:spring security Add automatic login and graphic verification code function to user login (spring boot 2.3.1)

    One , The purpose of captcha ? 1, What is graphic verification code ? Verification Code (CAPTCHA) yes "Completely Automated Public Turing test to tell Computers ...

  4. one hundred and fifteen :CMS Implementation of the system Click to change the graphic verification code function

    Render the CAPTCHA to the page visit , obviously , It's a label with an inner margin Remove the inner margin Add one more class If you zoom in , Do you have any questions use js Click to change the graphic verification code : Generate a query string to access the graphical captcha interface url, Put it in img mark ...

  5. SpringSceurity(4)--- SMS verification code function implementation

    SpringSceurity(4)--- SMS verification code function implementation of SpringSceurity There was an article written before the series 1.SpringSecurity(1)--- authentication + Authorization code implements 2.SpringSecur ...

  6. Django Learning notes (17)——BBS+Blog Project development (1) The realization of verification code function

    This paper mainly studies the realization of captcha function , For the project BBS+Blog The foundation of the project . In order to prevent robots from frequently landing on the website or damaging the malicious landing of molecules , Many user login and registration systems provide the function of graphic verification code . Verification Code (CAPTCHA) yes “Com ...

  7. .Net Core And Graphic verification code In this paper, .Net Core Use a third party ZKWeb.System.Drawing Realize the function of verification code .

    In this paper, .Net Core Use a third party ZKWeb.System.Drawing Realize the function of verification code . The system that passed the test : Windows 8.1 64bit Ubuntu Server 16.04 LTS 64 ...

  8. 【 Selfless sharing :ASP.NET CORE Project practice ( Chapter 14 )】 The realization of graphic verification code

    indexes [ Selfless sharing :ASP.NET CORE Project practice ] indexes brief introduction I haven't updated my blog for a long time , One is , I've been busy lately , Two is ,Core I have been groping for it all the time , In fact, a framework has been completed , And it's getting ready in a production environment ...

  9. Java Front end encryption transmission, back-end decryption and verification code function

    Catalog (?)[-] Encryption and decryption 1 front end js Encryption Overview 2 Front and back encryption and decryption 21 Refer to the js Encryption library 22 js Encryption and decryption 23 Java End encryption and decryption PKCS5Padding And js Of Pkcs7 Agreement Verification Code 1 General ...

Random recommendation

  1. $(document).ready(){}、$(fucntion(){})、(function(){})(jQuery)onload() The difference between

     1. The first said JQuery Several ways of writing   $(function(){     //do someting   });   $(document).ready(function(){     //do so ...

  2. Axure One o'clock

    My feelings : It's a great brain test , Concentrate in class 120 In spirit . Axure( Rapid prototyping of web pages ) 1: Global variables :a: You can create a new global variable in the menu bar . b: Control all pages . c: Take the value of the input box , Set up User The value of is equal to the value of the input box ...

  3. python Batch crawling agents ip

    import urllib.request import re import time import random def getResponse(url): req = urllib.request ...

  4. little&#39;s law( The law of lute )

    Reference resources :https://en.wikipedia.org/wiki/Little%27s_law( Take a look at this weekend ) I've been doing a performance stress test recently , At the beginning of the , The pressure doesn't go up , Reference resources : N = X * E[T] ,N It's your ...

  5. Data interaction ajax Code sorting

    Request list general /** ** Load the corresponding test paper set ** */ function loadQuestions(){ var businessSubClass = { pageNo:pageNo, pageS ...

  6. Struct2 towards Action Middle pass parameter ( Chinese code scrambling )

    Is to pass the values on the view to Action In the method of definition That is to transfer data from the foreground to the background Three ways : 1.   Use action Property to receive parameters such as jsp page : <body> Use action Property to receive parameters ...

  7. Basic sorting algorithm :Python Realization

    Basic sorting algorithm , Including bubble sorting , Insertion sort , Selection sort , Heap sort , Quick sorting, etc . [ Bubble sort ] Complexity is n*n #coding:utf8 #author:HaxtraZ #description: Bubble sort def ...

  8. What is the best Java email address validation method?

    https://stackoverflow.com/questions/624581/what-is-the-best-java-email-address-validation-method htt ...

  9. Gateway/Worker Model Examples of database usage

    From: http://www.bubuko.com/infodetail-777418.html 1. Database configuration Applications/XXX/Config/Db.php <?php na ...

  10. MyBatis in Like Sentence Usage Summary

    Native writing eg: select * from user where username like '%${value}%' Be careful :     ${value} It has to say value, Otherwise, it will report a mistake oracl ...