您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關SpringSecurity中怎么實現登錄添加驗證碼,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
準備驗證碼
要有驗證碼,首先得先準備好驗證碼,本文采用 Java 自畫的驗證碼,代碼如下:
/** * 生成驗證碼的工具類 */public class VerifyCode {private int width = 100;// 生成驗證碼圖片的寬度private int height = 50;// 生成驗證碼圖片的高度private String[] fontNames = { "宋體", "楷體", "隸書", "微軟雅黑" };private Color bgColor = new Color(255, 255, 255);// 定義驗證碼圖片的背景顏色為白色private Random random = new Random();private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";private String text;// 記錄隨機字符串/** * 獲取一個隨意顏色 * * @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);}/** * 獲取一個隨機字體 * * @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);}/** * 獲取一個隨機字符 * * @return */private char randomChar() {return codes.charAt(random.nextInt(codes.length()));}/** * 創建一個空白的BufferedImage對象 * * @return */private BufferedImage createImage() {BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D g2 = (Graphics2D) image.getGraphics();g2.setColor(bgColor);// 設置驗證碼圖片的背景顏色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;}/** * 繪制干擾線 * * @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);}}
這個工具類很常見,網上也有很多,就是畫一個簡單的驗證碼,通過流將驗證碼寫到前端頁面,提供驗證碼的 Controller 如下:
@RestControllerpublic 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()); }}
這里創建了一個 VerifyCode 對象,將生成的驗證碼字符保存到 session 中,然后通過流將圖片寫到前端,img標簽如下:
<img src="/vercode" alt="">
展示效果如下:
自定義過濾器
在登陸頁展示驗證碼這個就不需要我多說了,接下來我們來看看如何自定義驗證碼處理器:
@Componentpublic 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())) { // 驗證碼驗證 String requestCaptcha = request.getParameter("code"); String genCaptcha = (String) request.getSession().getAttribute("index_code"); if (StringUtils.isEmpty(requestCaptcha)) throw new AuthenticationServiceException("驗證碼不能為空!"); if (!genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())) { throw new AuthenticationServiceException("驗證碼錯誤!"); } } chain.doFilter(request, response); }}
自定義過濾器繼承自 GenericFilterBean ,并實現其中的 doFilter 方法,在 doFilter 方法中,當請求方法是 POST ,并且請求地址是 /doLogin 時,獲取參數中的 code 字段值,該字段保存了用戶從前端頁面傳來的驗證碼,然后獲取 session 中保存的驗證碼,如果用戶沒有傳來驗證碼,則拋出驗證碼不能為空異常,如果用戶傳入了驗證碼,則判斷驗證碼是否正確,如果不正確則拋出異常,否則執行 chain.doFilter(request, response); 使請求繼續向下走。
配置
最后在 Spring Security 的配置中,配置過濾器,如下:
@Configurationpublic 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); ,如此之后,整個配置就算完成了。
關于SpringSecurity中怎么實現登錄添加驗證碼就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。