Spring?Security圖形驗(yàn)證碼的實(shí)現(xiàn)代碼
生成圖形驗(yàn)證碼
添加maven依賴
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-config</artifactId>
<version>1.1.6.RELEASE</version>
</dependency>創(chuàng)建驗(yàn)證碼對(duì)象
/**
* @Author chen bo
* @Date 2023/12
* @Des
*/
@Data
public class ImageCode {
/**
* image圖片
*/
private BufferedImage image;
/**
* 驗(yàn)證碼
*/
private String code;
/**
* 過期時(shí)間
*/
private LocalDateTime expireTime;
public ImageCode(BufferedImage image, String code, int expireIn) {
this.image = image;
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
}
/**
* 判斷驗(yàn)證碼是否已過期
* @return
*/
public boolean isExpire() {
return LocalDateTime.now().isAfter(expireTime);
}
}創(chuàng)建ImageController
編寫接口,返回圖形驗(yàn)證碼:
/**
* @Author chen bo
* @Date 2023/12
* @Des
*/
@RestController
public class ImageController {
public final static String SESSION_KEY_IMAGE_CODE = "SESSION_VERIFICATION_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() {
// 驗(yàn)證碼圖片寬度
int width = 100;
// 驗(yàn)證碼圖片長度
int height = 36;
// 驗(yàn)證碼位數(shù)
int length = 4;
// 驗(yàn)證碼有效時(shí)間 60s
int expireIn = 60;
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);
}
}org.springframework.social.connect.web.HttpSessionSessionStrategy對(duì)象封裝了一些處理Session的方法,包含了setAttribute、getAttribute和removeAttribute方法,具體可以查看該類的源碼。使用sessionStrategy將生成的驗(yàn)證碼對(duì)象存儲(chǔ)到Session中,并通過IO流將生成的圖片輸出到登錄頁面上。
v改造登錄頁面
添加驗(yàn)證碼控件
在上一篇博文《SpringBoot進(jìn)階教程(八十一)Spring Security自定義認(rèn)證》中的"重寫form登錄頁",已經(jīng)創(chuàng)建了login.html,在login.html中添加如下代碼:
<span style="display: inline">
<input type="text" name="請(qǐng)輸入驗(yàn)證碼" placeholder="驗(yàn)證碼" required="required"/>
<img src="/code/image"/>
</span>img標(biāo)簽的src屬性對(duì)應(yīng)ImageController的createImageCode方法。
v認(rèn)證流程添加驗(yàn)證碼效驗(yàn)
定義異常類
在校驗(yàn)驗(yàn)證碼的過程中,可能會(huì)拋出各種驗(yàn)證碼類型的異常,比如“驗(yàn)證碼錯(cuò)誤”、“驗(yàn)證碼已過期”等,所以我們定義一個(gè)驗(yàn)證碼類型的異常類:
/**
* @Author chen bo
* @Date 2023/12
* @Des
*/
public class ValidateCodeException extends AuthenticationException {
private static final long serialVersionUID = 1715361291615299823L;
public ValidateCodeException(String explanation) {
super(explanation);
}
}注意:這里繼承的是AuthenticationException而不是Exception。
創(chuàng)建驗(yàn)證碼的校驗(yàn)過濾器
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:
/**
* @Author chen bo
* @Date 2023/12
* @Des
*/
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {
@Autowired
private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
if ("/login".equalsIgnoreCase(httpServletRequest.getRequestURI())
&& "post".equalsIgnoreCase(httpServletRequest.getMethod())) {
try {
validateCode(new ServletWebRequest(httpServletRequest));
} catch (ValidateCodeException e) {
myAuthenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
return;
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException, ValidateCodeException {
ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ImageController.SESSION_KEY_IMAGE_CODE);
String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imageCode");
if (StringUtils.isEmpty(codeInRequest)) {
throw new ValidateCodeException("驗(yàn)證碼不能為空!");
}
if (codeInSession == null) {
throw new ValidateCodeException("驗(yàn)證碼不存在!");
}
if (codeInSession.isExpire()) {
sessionStrategy.removeAttribute(servletWebRequest, ImageController.SESSION_KEY_IMAGE_CODE);
throw new ValidateCodeException("驗(yàn)證碼已過期!");
}
if (!codeInRequest.equalsIgnoreCase(codeInSession.getCode())) {
throw new ValidateCodeException("驗(yàn)證碼不正確!");
}
sessionStrategy.removeAttribute(servletWebRequest, ImageController.SESSION_KEY_IMAGE_CODE);
}
}ValidateCodeFilter繼承了org.springframework.web.filter.OncePerRequestFilter,該過濾器只會(huì)執(zhí)行一次。ValidateCodeFilter繼承了org.springframework.web.filter.OncePerRequestFilter,該過濾器只會(huì)執(zhí)行一次。
在doFilterInternal方法中我們判斷了請(qǐng)求URL是否為/login,該路徑對(duì)應(yīng)登錄form表單的action路徑,請(qǐng)求的方法是否為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)行處理。
我們分別從Session中獲取了ImageCode對(duì)象和請(qǐng)求參數(shù)imageCode(對(duì)應(yīng)登錄頁面的驗(yàn)證碼input框name屬性),然后進(jìn)行了各種判斷并拋出相應(yīng)的異常。當(dāng)驗(yàn)證碼過期或者驗(yàn)證碼校驗(yàn)通過時(shí),我們便可以刪除Session中的ImageCode屬性了。
v更新配置類
驗(yàn)證碼校驗(yàn)過濾器定義好了,怎么才能將其添加到UsernamePasswordAuthenticationFilter前面呢?很簡單,只需要在BrowserSecurityConfig的configure方法中添加些許配置即可,順便配置驗(yàn)證碼請(qǐng)求不配攔截: "/code/image"。
/**
* @Author chen bo
* @Date 2023/12
* @Des
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new ValidateCodeFilter(), UsernamePasswordAuthenticationFilter.class) //添加驗(yàn)證碼效驗(yàn)過濾器
.formLogin() // 表單登錄
.loginPage("/login.html") // 登錄跳轉(zhuǎn)url
// .loginPage("/authentication/require")
.loginProcessingUrl("/login") // 處理表單登錄url
// .successHandler(authenticationSuccessHandler)
.failureHandler(new MyAuthenticationFailureHandler())
.and()
.authorizeRequests() // 授權(quán)配置
.antMatchers("/login.html", "/css/**", "/authentication/require", "/code/image").permitAll() // 無需認(rèn)證
.anyRequest() // 所有請(qǐng)求
.authenticated() // 都需要認(rèn)證
.and().csrf().disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}上面代碼中,我們注入了ValidateCodeFilter,然后通過addFilterBefore方法將ValidateCodeFilter驗(yàn)證碼校驗(yàn)過濾器添加到了UsernamePasswordAuthenticationFilter前面。
v運(yùn)行效果圖

其他參考/學(xué)習(xí)資料:
- https://www.cnblogs.com/kikochz/p/12895842.html
- https://www.cnblogs.com/fanqisoft/p/10630556.html
- https://www.jianshu.com/p/5a83e364869c
v源碼地址
https://github.com/toutouge/javademosecond/tree/master/security-demo
到此這篇關(guān)于Spring Security圖形驗(yàn)證碼的文章就介紹到這了,更多相關(guān)Spring Security驗(yàn)證碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Spring?Security配置多個(gè)數(shù)據(jù)源并添加登錄驗(yàn)證碼的實(shí)例代碼
- Springboot+SpringSecurity實(shí)現(xiàn)圖片驗(yàn)證碼登錄的示例
- Spring Security 實(shí)現(xiàn)多種登錄方式(常規(guī)方式外的郵件、手機(jī)驗(yàn)證碼登錄)
- Spring Security添加驗(yàn)證碼的兩種方式小結(jié)
- Spring Security 實(shí)現(xiàn)短信驗(yàn)證碼登錄功能
- Spring Security登錄添加驗(yàn)證碼的實(shí)現(xiàn)過程
- SpringBoot + SpringSecurity 短信驗(yàn)證碼登錄功能實(shí)現(xiàn)
- SpringBoot結(jié)合SpringSecurity實(shí)現(xiàn)圖形驗(yàn)證碼功能
- SpringBoot+Security 發(fā)送短信驗(yàn)證碼的實(shí)現(xiàn)
- Spring Security OAuth2集成短信驗(yàn)證碼登錄以及第三方登錄
- Spring Security 圖片驗(yàn)證碼功能的實(shí)例代碼
相關(guān)文章
在IDEA中 實(shí)現(xiàn)給main方法附帶參數(shù)的操作
這篇文章主要介紹了在IDEA中 實(shí)現(xiàn)給main方法附帶參數(shù)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-01-01
關(guān)于MyBaties的基本配置標(biāo)簽總結(jié)
今天給大家?guī)淼氖顷P(guān)于MyBaties基礎(chǔ)的相關(guān)知識(shí),文章圍繞著MyBaties的基本配置標(biāo)簽展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
SpringBoot 下集成緩存工具類 CacheManager
這篇文章主要介紹了Springboot下集成緩存工具類CacheManager,想進(jìn)一步了解相關(guān)知識(shí)的同學(xué),可以詳細(xì)閱讀本文2023-03-03
Java Comparator.comparing比較導(dǎo)致空指針異常的解決
這篇文章主要介紹了Java Comparator.comparing比較導(dǎo)致空指針異常的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
通過Spring層面進(jìn)行事務(wù)回滾的實(shí)現(xiàn)
本文主要介紹了通過Spring層面進(jìn)行事務(wù)回滾的實(shí)現(xiàn),包括聲明式事務(wù)和編程式事務(wù),具有一定的參考價(jià)值,感興趣的可以了解一下2025-04-04

