1. 程式人生 > 程式設計 >Spring Security登入新增驗證碼的實現過程

Spring Security登入新增驗證碼的實現過程

登入新增驗證碼是一個非常常見的需求,網上也有非常成熟的解決方案,其實,要是自己自定義登入實現這個並不難,但是如果需要在 Spring Security 框架中實現這個功能,還得稍費一點功夫,本文就和小夥伴來分享下在 Spring Security 框架中如何新增驗證碼。

關於 Spring Security 基本配置,這裡就不再多說,小夥伴有不懂的可以參考我的書《SpringBoot+Vue全棧開發實戰》,本文主要來看如何加入驗證碼功能。

準備驗證碼

要有驗證碼,首先得先準備好驗證碼,本文采用 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,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 如下:

@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());
  }
}

這裡建立了一個 VerifyCode 物件,將生成的驗證碼字元儲存到 session 中,然後通過流將圖片寫到前端,img標籤如下:

<img src="/vercode" alt="">

展示效果如下:

自定義過濾器

在登陸頁展示驗證碼這個就不需要我多說了,接下來我們來看看如何自定義驗證碼處理器:

@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())) {
      // 驗證碼驗證
      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 的配置中,配置過濾器,如下:

@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); ,如此之後,整個配置就算完成了。

接下來在登入中,就需要傳入驗證碼了,如果不傳或者傳錯,都會丟擲異常,例如不傳的話,丟擲如下異常:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。