一文輕鬆學會:SpringBoot圖形驗證碼的生成

在很多情況下,我們需要生成圖形驗證碼來提高系統的安全程度,比如獲取手機驗證碼之前要輸入圖形驗證碼,比如答題或者抽獎之前要輸入圖形驗證碼,這樣子提高了用戶直接調用接口來刷的難度,為什麼說只是提高了難度呢,因為如果想要破解的話還是可以破解的,用智能識別,跟庫對比什麼的就可以破解了,只不過破解成本高!

再比如12306的圖形驗證碼是叫用戶選擇圖片類型的,這種難度就更加高了,若是破解的付出不能大於收益,正常來說用戶都不會去破解啦。

這裡實現的是最簡單的圖形驗證碼,後臺自動生成四位隨機數,然後合成圖片流返回給頁面,要注意的是這個驗證碼一定要後臺生成,不可以是前端傳過去,不然就沒有意義了,可以放session,也可以放入redis.

下面是代碼例子,我這個是基於SpringBoot的,不過其他框架也是一樣,主要是返回圖片流即可,這裡還要注意加上一個配置類。

頁面的使用方式可以直接是:將這個請求路徑寫在img標籤的src中,每次刷新就改變src的值,後面加一個時間戳。

<code>http://localhost:8080/get/<code>

代碼如下:

<code>@RestController
public class MyController {
@RequestMapping(value = "/get",produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public BufferedImage getImage() throws IOException {
SecureRandom random = new SecureRandom();
//圖形驗證碼的寬度
int width=75;

//圖形驗證碼的高度
int height = 30;
//圖形驗證碼的顏色
Color backColor = new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
//圖形驗證碼的字體顏色,跟背景顏色反色
Color fontColor = new Color(255-backColor.getRed(),255-backColor.getGreen(),255-backColor.getBlue());
//生成BufferedImage對象
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//得到畫布
Graphics2D g = bi.createGraphics();
//獲取字體:Sans Serif字體比較難以閱讀,增加辨識難度
Font font = new Font(Font.SANS_SERIF, Font.BOLD, 20);
//設置字體
g.setFont(font);
//設置畫筆顏色
g.setColor(backColor);
//畫背景
g.fillRect(0, 0, width, height);
//設置畫筆顏色
g.setColor(fontColor);
//獲取要畫的驗證碼
String seq = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ";
StringBuffer sb = new StringBuffer();
int j = 0;
for(int i=0;i<4;i++) {
j=random.nextInt(seq.length());
sb.append(seq.substring(j, j+1));
}
String code = sb.toString();
//畫字符:畫布寬度75,高度30,文字大小20,四個文字長度就是
//計算文字長度
FontMetrics fm = g.getFontMetrics(font);
int textWidth = fm.stringWidth(code);
int w = (width-textWidth)/2;
g.drawString(code, w, 22);
//畫噪點:40個
for(int i=0;i<40;i++) {
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));

g.fillRect(random.nextInt(width), random.nextInt(height), 1, 1);
}
//返回圖片流
return bi;
}
}
@Configuration
class My extends WebMvcConfigurationSupport{
@Override
protected void extendMessageConverters(List<httpmessageconverter>> converters) {
converters.add(new BufferedImageHttpMessageConverter());
}
}/<httpmessageconverter>/<code>

注意事項:

有時候如果我們直接使用繼承WebMvcConfigurationSupport會影響資源文件的加載。此時我們可以改為實現:WebMvcConfiger

<code>public class My implements WebMvcConfiger{
...
  @Override
public void extendMessageConverters(List<httpmessageconverter>> converters) {
converters.add(new BufferedImageHttpMessageConverter());
}
...
}/<httpmessageconverter>/<code>


啟動測試:

這裡就直接瀏覽器訪問如下鏈接即可

<code>http://localhost:8080/get/<code>


一文輕鬆學會:SpringBoot圖形驗證碼的生成


分享到:


相關文章: