spring登录验证码怎么实现
-
要实现Spring登录验证码,可以按照以下步骤进行操作:
-
添加验证码依赖:在项目的pom.xml文件中添加验证码相关依赖,如spring-boot-starter-validation、kaptcha等。
-
创建验证码配置类:新建一个配置类,用于配置验证码的相关参数,如图片宽度、高度、字符长度、干扰线数量等。
-
生成验证码图片:创建一个生成验证码图片的方法,利用kaptcha生成随机字符,并将字符生成验证码图片。
-
显示验证码图片:将生成的验证码图片以Base64格式返回给前端页面,在登录页面上将验证码图片进行展示。
-
校验验证码:在登录接口中接收前端传递的验证码参数,与Session中保存的验证码进行比对,判断验证码的正确性。
下面是一个简单的示例代码,演示了如何在Spring Boot中实现登录验证码:
- 添加验证码相关依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>- 创建验证码配置类:
@Configuration public class CaptchaConfig { @Value("${captcha.width}") private String width; @Value("${captcha.height}") private String height; @Value("${captcha.length}") private String length; @Value("${captcha.lines}") private String lines; @Value("${captcha.font.size}") private String fontSize; @Bean public DefaultKaptcha kaptcha() { Properties properties = new Properties(); properties.setProperty("kaptcha.image.width", width); properties.setProperty("kaptcha.image.height", height); properties.setProperty("kaptcha.textproducer.char.length", length); properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise"); properties.setProperty("kaptcha.noise.color", "white"); properties.setProperty("kaptcha.background.clear.from", "white"); properties.setProperty("kaptcha.background.clear.to", "white"); properties.setProperty("kaptcha.textproducer.font.size", fontSize); properties.setProperty("kaptcha.textproducer.font.names", "Arial, Courier"); properties.setProperty("kaptcha.textproducer.char.string", "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789"); properties.setProperty("kaptcha.textproducer.char.space", "5"); DefaultKaptcha kaptcha = new DefaultKaptcha(); Config config = new Config(properties); kaptcha.setConfig(config); return kaptcha; } }- 生成验证码图片:
@Controller public class CaptchaController { @Autowired private DefaultKaptcha kaptcha; @RequestMapping("/captcha") public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); String text = kaptcha.createText(); request.getSession().setAttribute("captcha", text); BufferedImage image = kaptcha.createImage(text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); out.flush(); out.close(); } }- 显示验证码图片:
在登录页面的HTML中,添加一个标签来显示验证码图片:
<img src="/captcha" onclick="this.src='/captcha?'+Math.random()" />- 校验验证码:
@RequestMapping("/login") @ResponseBody public String login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("captcha") String captcha, HttpServletRequest request) { String sessionCaptcha = (String) request.getSession().getAttribute("captcha"); if (sessionCaptcha.equalsIgnoreCase(captcha)) { // 验证码正确,进行登录逻辑 // ... } else { // 验证码错误,返回错误信息 // ... } }通过以上步骤,就可以在Spring中实现登录验证码功能了。当用户访问登录页面时,会生成一个验证码图片,用户输入验证码后进行校验,确保登录过程更加安全。
1年前 -
-
在Spring框架中实现登录验证码可以通过以下步骤:
- 添加依赖:首先需要在项目的pom.xml文件中添加验证码相关的依赖。常用的验证码库有Google的reCaptcha和Kaptcha。例如,可以添加以下依赖项来使用Kaptcha:
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>- 配置验证码生成器:在Spring的配置文件中添加验证码生成器的配置。对于Kaptcha,可以使用以下配置来定义验证码生成器的属性:
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="border" value="no"/> <property name="textProducerImpl"> <bean class="com.google.code.kaptcha.text.impl.DefaultTextCreator"/> </property> <property name="textProducer"> <bean class="com.google.code.kaptcha.text.impl.DefaultTextProducer"> <property name="length" value="4"/> <property name="charString" value="0123456789"/> </bean> </property> <property name="backgroundProducer"> <bean class="com.google.code.kaptcha.impl.DefaultBackground"/> </property> <property name="sessionKey" value="captchaCode"/> <property name="width" value="80"/> <property name="height" value="35"/> <property name="textProducerFontSize" value="30"/> <property name="textProducerFontColor" value="black"/> <property name="textProducerCharSpace" value="5"/> <property name="noiseProducer" ref="noiseProducer"/> </bean> <bean id="noiseProducer" class="com.google.code.kaptcha.impl.DefaultNoise"> <property name="colorFactory"> <bean class="com.google.code.kaptcha.impl.DefaultColorFactory"> <property name="noiseColor" value="black"/> </bean> </property> </bean>- 生成验证码图片:可以通过在Controller中使用以下代码来生成验证码图片,并将验证码文本保存到Session中:
@Controller public class CaptchaController { @RequestMapping("/captcha.jpg") public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException { Config config = new Config(); DefaultKaptcha captchaProducer = new DefaultKaptcha(); captchaProducer.setConfig(config); String text = captchaProducer.createText(); BufferedImage image = captchaProducer.createImage(text); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", out); byte[] captchaBytes = out.toByteArray(); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaBytes); responseOutputStream.flush(); responseOutputStream.close(); HttpSession session = request.getSession(); session.setAttribute("captchaCode", text); } }- 验证用户输入的验证码:在用户登录时,可以通过以下代码来验证用户输入的验证码是否与Session中保存的一致:
@Controller public class LoginController { @RequestMapping("/login") public String login(HttpServletRequest request, Model model) { String username = request.getParameter("username"); String password = request.getParameter("password"); String captcha = request.getParameter("captcha"); HttpSession session = request.getSession(); String captchaCode = (String) session.getAttribute("captchaCode"); if (!captcha.equals(captchaCode)) { model.addAttribute("errMsg", "验证码错误"); return "login"; } // 验证通过,进行登录逻辑 return "home"; } }- 在登录页面中显示验证码:在登录页面的HTML代码中,可以通过以下代码来显示验证码图片,并在表单中添加一个验证码输入框:
<img src="/captcha.jpg" alt="验证码"> <input type="text" name="captcha" placeholder="请输入验证码">通过以上步骤,就可以在Spring框架中实现登录验证码功能。用户在登录时需要输入正确的验证码才能进行登录,防止恶意登录和暴力破解。
1年前 -
实现Spring登录验证码可以通过以下步骤进行:
- 添加相关依赖
在项目的pom.xml文件中添加Spring Security、Spring Boot Starter Web 和 Thymeleaf的依赖:
<dependencies> <!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>- 创建登录页面
在src/main/resources/templates目录下创建login.html文件,并编写登录页面代码,包括用户名、密码和验证码输入框以及登录按钮。
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Login</title> </head> <body> <h2>Login</h2> <form th:action="@{/login}" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username" required/> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password" required/> </div> <div> <label for="captcha">Captcha:</label> <input type="text" id="captcha" name="captcha" required/> <img th:src="@{/captcha}" alt="captcha"/> </div> <div> <button type="submit">Login</button> </div> </form> </body> </html>- 添加验证码生成器
创建一个CaptchaGenerator类,用于生成验证码图片和保存验证码文本。
import java.awt.*; import java.awt.image.BufferedImage; import java.util.Random; public class CaptchaGenerator { private static final int WIDTH = 120; private static final int HEIGHT = 40; private static final int CODE_LENGTH = 4; private static final char[] CODE_SEQUENCE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray(); public static BufferedImage generateCaptchaImage() { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); Random random = new Random(); // 绘制背景 g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); // 绘制干扰线 for (int i = 0; i < 6; i++) { g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256))); g.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), random.nextInt(WIDTH), random.nextInt(HEIGHT)); } // 绘制验证码 StringBuilder codeBuilder = new StringBuilder(); for (int i = 0; i < CODE_LENGTH; i++) { char codeChar = CODE_SEQUENCE[random.nextInt(CODE_SEQUENCE.length)]; codeBuilder.append(codeChar); g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256))); g.drawString(String.valueOf(codeChar), 20 * i + 10, 30); } g.dispose(); // 保存验证码文本 String captchaCode = codeBuilder.toString(); // 可以将验证码保存到数据库或者缓存中,方便后续校验 return image; } }- 创建验证码控制器
创建一个CaptchaController类,用于处理验证码相关的请求,并返回验证码图片。
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller public class CaptchaController { @GetMapping("/captcha") public void getCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image = CaptchaGenerator.generateCaptchaImage(); ServletOutputStream outputStream = response.getOutputStream(); ImageIO.write(image, "jpg", outputStream); outputStream.close(); } }- 创建登录控制器
创建一个LoginController类,用于处理登录请求,并进行验证码校验。
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class LoginController { @GetMapping("/login") public String showLoginPage() { return "login"; } @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password, @RequestParam String captcha, RedirectAttributes attributes) { // 校验验证码 String storedCaptcha = "从数据库或缓存中获取保存的验证码"; if (!captcha.equals(storedCaptcha)) { attributes.addFlashAttribute("error", "验证码错误"); return "redirect:/login"; } // 其他登录逻辑 return "redirect:/home"; } }以上就是利用Spring实现登录验证码的方法和操作流程。通过添加相关依赖,创建登录页面、验证码生成器和相关控制器,可以实现登录验证码的功能。
1年前