Spring Security登錄添加驗(yàn)證碼的實(shí)現(xiàn)過(guò)程
登錄添加驗(yàn)證碼是一個(gè)非常常見(jiàn)的需求,網(wǎng)上也有非常成熟的解決方案,其實(shí),要是自己自定義登錄實(shí)現(xiàn)這個(gè)并不難,但是如果需要在 Spring Security 框架中實(shí)現(xiàn)這個(gè)功能,還得稍費(fèi)一點(diǎn)功夫,本文就和小伙伴來(lái)分享下在 Spring Security 框架中如何添加驗(yàn)證碼。
關(guān)于 Spring Security 基本配置,這里就不再多說(shuō),小伙伴有不懂的可以參考我的書(shū)《SpringBoot+Vue全棧開(kāi)發(fā)實(shí)戰(zhàn)》,本文主要來(lái)看如何加入驗(yàn)證碼功能。
準(zhǔn)備驗(yàn)證碼
要有驗(yàn)證碼,首先得先準(zhǔn)備好驗(yàn)證碼,本文采用 Java 自畫(huà)的驗(yàn)證碼,代碼如下:
/** * 生成驗(yàn)證碼的工具類(lèi) */ public class VerifyCode { private int width = 100;// 生成驗(yàn)證碼圖片的寬度 private int height = 50;// 生成驗(yàn)證碼圖片的高度 private String[] fontNames = { "宋體", "楷體", "隸書(shū)", "微軟雅黑" }; private Color bgColor = new Color(255, 255, 255);// 定義驗(yàn)證碼圖片的背景顏色為白色 private Random random = new Random(); private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private String text;// 記錄隨機(jī)字符串 /** * 獲取一個(gè)隨意顏色 * * @return */ private Color randomColor() { int red = random.nextInt(150); int green = random.nextInt(150); int blue = random.nextInt(150); return new Color(red, green, blue); } /** * 獲取一個(gè)隨機(jī)字體 * * @return */ private Font randomFont() { String name = fontNames[random.nextInt(fontNames.length)]; int style = random.nextInt(4); int size = random.nextInt(5) + 24; return new Font(name, style, size); } /** * 獲取一個(gè)隨機(jī)字符 * * @return */ private char randomChar() { return codes.charAt(random.nextInt(codes.length())); } /** * 創(chuàng)建一個(gè)空白的BufferedImage對(duì)象 * * @return */ private BufferedImage createImage() { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setColor(bgColor);// 設(shè)置驗(yàn)證碼圖片的背景顏色 g2.fillRect(0, 0, width, height); return image; } public BufferedImage getImage() { BufferedImage image = createImage(); Graphics2D g2 = (Graphics2D) image.getGraphics(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < 4; i++) { String s = randomChar() + ""; sb.append(s); g2.setColor(randomColor()); g2.setFont(randomFont()); float x = i * width * 1.0f / 4; g2.drawString(s, x, height - 15); } this.text = sb.toString(); drawLine(image); return image; } /** * 繪制干擾線(xiàn) * * @param image */ private void drawLine(BufferedImage image) { Graphics2D g2 = (Graphics2D) image.getGraphics(); int num = 5; for (int i = 0; i < num; i++) { int x1 = random.nextInt(width); int y1 = random.nextInt(height); int x2 = random.nextInt(width); int y2 = random.nextInt(height); g2.setColor(randomColor()); g2.setStroke(new BasicStroke(1.5f)); g2.drawLine(x1, y1, x2, y2); } } public String getText() { return text; } public static void output(BufferedImage image, OutputStream out) throws IOException { ImageIO.write(image, "JPEG", out); } }
這個(gè)工具類(lèi)很常見(jiàn),網(wǎng)上也有很多,就是畫(huà)一個(gè)簡(jiǎn)單的驗(yàn)證碼,通過(guò)流將驗(yàn)證碼寫(xiě)到前端頁(yè)面,提供驗(yàn)證碼的 Controller 如下:
@RestController public class VerifyCodeController { @GetMapping("/vercode") public void code(HttpServletRequest req, HttpServletResponse resp) throws IOException { VerifyCode vc = new VerifyCode(); BufferedImage image = vc.getImage(); String text = vc.getText(); HttpSession session = req.getSession(); session.setAttribute("index_code", text); VerifyCode.output(image, resp.getOutputStream()); } }
這里創(chuàng)建了一個(gè) VerifyCode 對(duì)象,將生成的驗(yàn)證碼字符保存到 session 中,然后通過(guò)流將圖片寫(xiě)到前端,img標(biāo)簽如下:
<img src="/vercode" alt="">
展示效果如下:
自定義過(guò)濾器
在登陸頁(yè)展示驗(yàn)證碼這個(gè)就不需要我多說(shuō)了,接下來(lái)我們來(lái)看看如何自定義驗(yàn)證碼處理器:
@Component public class VerifyCodeFilter extends GenericFilterBean { private String defaultFilterProcessUrl = "/doLogin"; @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) { // 驗(yàn)證碼驗(yàn)證 String requestCaptcha = request.getParameter("code"); String genCaptcha = (String) request.getSession().getAttribute("index_code"); if (StringUtils.isEmpty(requestCaptcha)) throw new AuthenticationServiceException("驗(yàn)證碼不能為空!"); if (!genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())) { throw new AuthenticationServiceException("驗(yàn)證碼錯(cuò)誤!"); } } chain.doFilter(request, response); } }
自定義過(guò)濾器繼承自 GenericFilterBean ,并實(shí)現(xiàn)其中的 doFilter 方法,在 doFilter 方法中,當(dāng)請(qǐng)求方法是 POST ,并且請(qǐng)求地址是 /doLogin 時(shí),獲取參數(shù)中的 code 字段值,該字段保存了用戶(hù)從前端頁(yè)面?zhèn)鱽?lái)的驗(yàn)證碼,然后獲取 session 中保存的驗(yàn)證碼,如果用戶(hù)沒(méi)有傳來(lái)驗(yàn)證碼,則拋出驗(yàn)證碼不能為空異常,如果用戶(hù)傳入了驗(yàn)證碼,則判斷驗(yàn)證碼是否正確,如果不正確則拋出異常,否則執(zhí)行 chain.doFilter(request, response); 使請(qǐng)求繼續(xù)向下走。
配置
最后在 Spring Security 的配置中,配置過(guò)濾器,如下:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired VerifyCodeFilter verifyCodeFilter; ... ... @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class); http.authorizeRequests() .antMatchers("/admin/**").hasRole("admin") ... ... .permitAll() .and() .csrf().disable(); } }
這里只貼出了部分核心代碼,即 http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class); ,如此之后,整個(gè)配置就算完成了。
接下來(lái)在登錄中,就需要傳入驗(yàn)證碼了,如果不傳或者傳錯(cuò),都會(huì)拋出異常,例如不傳的話(huà),拋出如下異常:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Spring Security 實(shí)現(xiàn)多種登錄方式(常規(guī)方式外的郵件、手機(jī)驗(yàn)證碼登錄)
- Spring Security 實(shí)現(xiàn)短信驗(yàn)證碼登錄功能
- SpringBoot + SpringSecurity 短信驗(yàn)證碼登錄功能實(shí)現(xiàn)
- Spring Security OAuth2集成短信驗(yàn)證碼登錄以及第三方登錄
- Spring Security Oauth2.0 實(shí)現(xiàn)短信驗(yàn)證碼登錄示例
- 使用Spring Security集成手機(jī)驗(yàn)證碼登錄功能實(shí)現(xiàn)
相關(guān)文章
Spring Security基于JWT實(shí)現(xiàn)SSO單點(diǎn)登錄詳解
這篇文章主要介紹了Spring Security基于JWT實(shí)現(xiàn)SSO單點(diǎn)登錄詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09Mybatis如何按順序查詢(xún)出對(duì)應(yīng)的數(shù)據(jù)字段
這篇文章主要介紹了Mybatis如何按順序查詢(xún)出對(duì)應(yīng)的數(shù)據(jù)字段,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01一文帶你了解Spring中Bean名稱(chēng)加載機(jī)制
這篇文章主要給大家介紹了Spring Framework如何從使用注解定義的Bean元數(shù)據(jù)中獲取到Bean的名稱(chēng),文中通過(guò)代碼示例給大家介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2024-01-01Java實(shí)現(xiàn)在正則表達(dá)式中控制大小寫(xiě)的方法
這篇文章主要介紹了Java實(shí)現(xiàn)在正則表達(dá)式中控制大小寫(xiě)的方法,結(jié)合實(shí)例形式分析了java正則表達(dá)式中傳遞控制參數(shù)的功能與相關(guān)操作技巧,需要的朋友可以參考下2017-04-04Java實(shí)現(xiàn)簡(jiǎn)單小畫(huà)板
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡(jiǎn)單小畫(huà)板,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06