登錄添加驗證碼是一個非常常見的需求,網上也有非常成熟的解決方案。在傳統的登錄流程中加入一個登錄驗證碼也不是難事,但是如何在 Spring Security 中添加登錄驗證碼,對於初學者來說還是一件蠻有挑戰的事情,因爲默認情況下,在 Spring Security 中我們並不需要自己寫登錄認證邏輯,只需要自己稍微配置一下就可以了,所以如果要添加登錄驗證碼,就涉及到如何在 Spring Security 即有的認證體系中,加入自己的驗證邏輯。
準備驗證碼
要有驗證碼,首先得先準備好驗證碼,本文采用 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 如下:
@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 = "/login";
@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,並且請求地址是 /login時,獲取參數中的 code 字段值,該字段保存了用戶從前端頁面傳來的驗證碼,然後獲取 session 中保存的驗證碼,如果用戶沒有傳來驗證碼,則拋出驗證碼不能爲空異常,如果用戶傳入了驗證碼,則判斷驗證碼是否正確,如果不正確則拋出異常,否則執行 chain.doFilter(request, response); 使請求繼續向下走。
配置
最後在 Spring Security 的配置中,配置過濾器,如下:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private VerifyCodeFilter verifyCodeFilter;
@Bean
PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("javakf")
.password("123").roles("admin");
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/vercode.html", "/vercode");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.csrf().disable();
}
}
這裏只貼出了部分核心代碼,即 http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
,如此之後,整個配置就算完成了。
測試
接下來在登錄中,就需要傳入驗證碼了,如果不傳或者傳錯,都會拋出異常,例如不傳的話,拋出如下異常:
org.springframework.security.authentication.AuthenticationServiceException: 驗證碼不能爲空!