- 生成圖形驗(yàn)證碼
- 改造登陸頁
- 認(rèn)證流程添加驗(yàn)證碼校驗(yàn)
添加驗(yàn)證碼大致可以分為三個(gè)步驟:根據(jù)隨機(jī)數(shù)生成驗(yàn)證碼圖片砾肺;將驗(yàn)證碼圖片顯示到登錄頁面;認(rèn)證流程中加入驗(yàn)證碼校驗(yàn)。Spring Security的認(rèn)證校驗(yàn)是由UsernamePasswordAuthenticationFilter過濾器完成的,所以我們的驗(yàn)證碼校驗(yàn)邏輯應(yīng)該在這個(gè)過濾器之前。
生成圖形驗(yàn)證碼
添加依賴
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-config</artifactId>
<version>1.1.6.RELEASE</version>
</dependency>
創(chuàng)建一個(gè)驗(yàn)證碼對象ImageCode:
@Data
public class ImageCode {
private BufferedImage image;
private String code;
private LocalDateTime expireTime;
public ImageCode(BufferedImage image, String code, int expireIn) {
this.image = image;
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
}
boolean isExpire() {
return LocalDateTime.now().isAfter(expireTime);
}
}
ImageCode對象包含了三個(gè)屬性:image圖片窿祥,code驗(yàn)證碼和expireTime過期時(shí)間。isExpire方法用于判斷驗(yàn)證碼是否已過期蝙寨。
創(chuàng)建ValidateController晒衩,編寫接口,返回圖形驗(yàn)證碼:
@RestController
public class ValidateController {
public final static String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@GetMapping("/code/image")
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
ImageCode imageCode = createImageCode();
sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_IMAGE_CODE, imageCode);
ImageIO.write(imageCode.getImage(), "jpeg", response.getOutputStream());
}
private ImageCode createImageCode() {
int width = 100; // 驗(yàn)證碼圖片寬度
int height = 36; // 驗(yàn)證碼圖片長度
int length = 4; // 驗(yàn)證碼位數(shù)
int expireIn = 60; // 驗(yàn)證碼有效時(shí)間 60s
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
Random random = new Random();
graphics.setColor(getRandColor(200, 500));
graphics.fillRect(0, 0, width, height);
graphics.setFont(new Font("Times New Roman", Font.ITALIC, 20));
graphics.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
graphics.drawLine(x, y, x + xl, y + yl);
}
StringBuilder sRand = new StringBuilder();
for (int i = 0; i < length; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand.append(rand);
graphics.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
graphics.drawString(rand, 13 * i + 6, 16);
}
graphics.dispose();
return new ImageCode(image, sRand.toString(), expireIn);
}
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
createImageCode方法用于生成驗(yàn)證碼對象墙歪,org.springframework.social.connect.web.HttpSessionSessionStrategy對象封裝了一些處理Session的方法听系,包含了setAttribute、getAttribute和removeAttribute方法虹菲,具體可以查看該類的源碼靠胜。使用sessionStrategy將生成的驗(yàn)證碼對象存儲到Session中,并通過IO流將生成的圖片輸出到登錄頁面上。
改造登錄頁面
在登錄頁面添加如下代碼:
<span style="display: inline">
<input type="text" name="imageCode" placeholder="驗(yàn)證碼" style="width: 50%;"/>
<img src="/code/image"/>
</span>
<img>標(biāo)簽的src屬性對應(yīng)ValidateController的createImageCode方法浪漠。
配置驗(yàn)證碼請求不配攔截: "/code/image"
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) //添加驗(yàn)證碼效驗(yàn)過濾器
.formLogin() // 表單登錄
.loginPage("/login.html") // 登錄跳轉(zhuǎn)url
// .loginPage("/authentication/require")
.loginProcessingUrl("/login") // 處理表單登錄url
// .successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.and()
.authorizeRequests() // 授權(quán)配置
.antMatchers("/login.html", "/css/**", "/authentication/require", "/code/image").permitAll() // 無需認(rèn)證
.anyRequest() // 所有請求
.authenticated() // 都需要認(rèn)證
.and().csrf().disable();
}
重啟項(xiàng)目陕习,訪問登錄:
認(rèn)證流程添加驗(yàn)證碼效驗(yàn)
在校驗(yàn)驗(yàn)證碼的過程中,可能會拋出各種驗(yàn)證碼類型的異常址愿,比如“驗(yàn)證碼錯誤”该镣、“驗(yàn)證碼已過期”等,所以我們定義一個(gè)驗(yàn)證碼類型的異常類:
public class ValidateCodeException extends AuthenticationException {
private static final long serialVersionUID = 2672899097153524723L;
public ValidateCodeException(String explanation) {
super(explanation);
}
}
注意响谓,這里繼承的是AuthenticationException而不是Exception损合。
我們都知道,Spring Security實(shí)際上是由許多過濾器組成的過濾器鏈娘纷,處理用戶登錄邏輯的過濾器為UsernamePasswordAuthenticationFilter嫁审,而驗(yàn)證碼校驗(yàn)過程應(yīng)該是在這個(gè)過濾器之前的,即只有驗(yàn)證碼校驗(yàn)通過后才去校驗(yàn)用戶名和密碼失驶。由于Spring Security并沒有直接提供驗(yàn)證碼校驗(yàn)相關(guān)的過濾器接口土居,所以我們需要自己定義一個(gè)驗(yàn)證碼校驗(yàn)的過濾器ValidateCodeFilter:
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {
@Autowired
private AuthenticationFailureHandler authenticationFailureHandler;
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
if (StringUtils.equalsIgnoreCase("/login", httpServletRequest.getRequestURI())
&& StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
try {
validateCode(new ServletWebRequest(httpServletRequest));
} catch (ValidateCodeException e) {
authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
return;
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException, ValidateCodeException {
......
}
}
ValidateCodeFilter繼承了org.springframework.web.filter.OncePerRequestFilter枣购,該過濾器只會執(zhí)行一次嬉探。
在doFilterInternal方法中我們判斷了請求URL是否為/login,該路徑對應(yīng)登錄form表單的action路徑棉圈,請求的方法是否為POST涩堤,是的話進(jìn)行驗(yàn)證碼校驗(yàn)邏輯,否則直接執(zhí)行filterChain.doFilter讓代碼往下走分瘾。當(dāng)在驗(yàn)證碼校驗(yàn)的過程中捕獲到異常時(shí)胎围,調(diào)用Spring Security的校驗(yàn)失敗處理器AuthenticationFailureHandler進(jìn)行處理。
validateCode的校驗(yàn)邏輯如下所示:
private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException, ValidateCodeException {
ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imageCode");
if (StringUtils.isBlank(codeInRequest)) {
throw new ValidateCodeException("驗(yàn)證碼不能為空德召!");
}
if (codeInSession == null) {
throw new ValidateCodeException("驗(yàn)證碼不存在白魂!");
}
if (codeInSession.isExpire()) {
sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
throw new ValidateCodeException("驗(yàn)證碼已過期!");
}
if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), codeInRequest)) {
throw new ValidateCodeException("驗(yàn)證碼不正確上岗!");
}
sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
}
我們分別從Session中獲取了ImageCode對象和請求參數(shù)imageCode(對應(yīng)登錄頁面的驗(yàn)證碼<input>框name屬性),然后進(jìn)行了各種判斷并拋出相應(yīng)的異常福荸。當(dāng)驗(yàn)證碼過期或者驗(yàn)證碼校驗(yàn)通過時(shí),我們便可以刪除Session中的ImageCode屬性了肴掷。
驗(yàn)證碼校驗(yàn)過濾器定義好了敬锐,怎么才能將其添加到UsernamePasswordAuthenticationFilter前面呢?很簡單呆瞻,只需要在BrowserSecurityConfig的configure方法中添加些許配置即可:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) //添加驗(yàn)證碼效驗(yàn)過濾器
.formLogin() // 表單登錄
.loginPage("/login.html") // 登錄跳轉(zhuǎn)url
// .loginPage("/authentication/require")
.loginProcessingUrl("/login") // 處理表單登錄url
// .successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.and()
.authorizeRequests() // 授權(quán)配置
.antMatchers("/login.html", "/css/**", "/authentication/require", "/code/image").permitAll() // 無需認(rèn)證
.anyRequest() // 所有請求
.authenticated() // 都需要認(rèn)證
.and().csrf().disable();
}
上面代碼中台夺,我們注入了ValidateCodeFilter,然后通過addFilterBefore方法將ValidateCodeFilter驗(yàn)證碼校驗(yàn)過濾器添加到了UsernamePasswordAuthenticationFilter前面痴脾。
重啟項(xiàng)目颤介,當(dāng)不輸入驗(yàn)證碼的時(shí)候,返回:
輸入錯誤驗(yàn)證碼的時(shí)候:
源碼地址:https://github.com/lbshold/springboot/tree/master/Spring-Security-ValidateCode
參考文章:
https://www.cnblogs.com/wutianqi/p/9186645.html
https://mrbird.cc/Spring-Security-ValidateCode.html