Spring?Security圖形驗證碼的實現(xiàn)代碼
生成圖形驗證碼
添加maven依賴
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-config</artifactId>
<version>1.1.6.RELEASE</version>
</dependency>創(chuàng)建驗證碼對象
/**
* @Author chen bo
* @Date 2023/12
* @Des
*/
@Data
public class ImageCode {
/**
* image圖片
*/
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);
}
/**
* 判斷驗證碼是否已過期
* @return
*/
public boolean isExpire() {
return LocalDateTime.now().isAfter(expireTime);
}
}創(chuàng)建ImageController
編寫接口,返回圖形驗證碼:
/**
* @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() {
// 驗證碼圖片寬度
int width = 100;
// 驗證碼圖片長度
int height = 36;
// 驗證碼位數(shù)
int length = 4;
// 驗證碼有效時間 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對象封裝了一些處理Session的方法,包含了setAttribute、getAttribute和removeAttribute方法,具體可以查看該類的源碼。使用sessionStrategy將生成的驗證碼對象存儲到Session中,并通過IO流將生成的圖片輸出到登錄頁面上。
v改造登錄頁面
添加驗證碼控件
在上一篇博文《SpringBoot進階教程(八十一)Spring Security自定義認(rèn)證》中的"重寫form登錄頁",已經(jīng)創(chuàng)建了login.html,在login.html中添加如下代碼:
<span style="display: inline">
<input type="text" name="請輸入驗證碼" placeholder="驗證碼" required="required"/>
<img src="/code/image"/>
</span>img標(biāo)簽的src屬性對應(yīng)ImageController的createImageCode方法。
v認(rè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)建驗證碼的校驗過濾器
Spring Security實際上是由許多過濾器組成的過濾器鏈,處理用戶登錄邏輯的過濾器為UsernamePasswordAuthenticationFilter,而驗證碼校驗過程應(yīng)該是在這個過濾器之前的,即只有驗證碼校驗通過后才去校驗用戶名和密碼。由于Spring Security并沒有直接提供驗證碼校驗相關(guā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("驗證碼不能為空!");
}
if (codeInSession == null) {
throw new ValidateCodeException("驗證碼不存在!");
}
if (codeInSession.isExpire()) {
sessionStrategy.removeAttribute(servletWebRequest, ImageController.SESSION_KEY_IMAGE_CODE);
throw new ValidateCodeException("驗證碼已過期!");
}
if (!codeInRequest.equalsIgnoreCase(codeInSession.getCode())) {
throw new ValidateCodeException("驗證碼不正確!");
}
sessionStrategy.removeAttribute(servletWebRequest, ImageController.SESSION_KEY_IMAGE_CODE);
}
}ValidateCodeFilter繼承了org.springframework.web.filter.OncePerRequestFilter,該過濾器只會執(zhí)行一次。ValidateCodeFilter繼承了org.springframework.web.filter.OncePerRequestFilter,該過濾器只會執(zhí)行一次。
在doFilterInternal方法中我們判斷了請求URL是否為/login,該路徑對應(yīng)登錄form表單的action路徑,請求的方法是否為POST,是的話進行驗證碼校驗邏輯,否則直接執(zhí)行filterChain.doFilter讓代碼往下走。當(dāng)在驗證碼校驗的過程中捕獲到異常時,調(diào)用Spring Security的校驗失敗處理器AuthenticationFailureHandler進行處理。
我們分別從Session中獲取了ImageCode對象和請求參數(shù)imageCode(對應(yīng)登錄頁面的驗證碼input框name屬性),然后進行了各種判斷并拋出相應(yīng)的異常。當(dāng)驗證碼過期或者驗證碼校驗通過時,我們便可以刪除Session中的ImageCode屬性了。
v更新配置類
驗證碼校驗過濾器定義好了,怎么才能將其添加到UsernamePasswordAuthenticationFilter前面呢?很簡單,只需要在BrowserSecurityConfig的configure方法中添加些許配置即可,順便配置驗證碼請求不配攔截: "/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) //添加驗證碼效驗過濾器
.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() // 所有請求
.authenticated() // 都需要認(rèn)證
.and().csrf().disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}上面代碼中,我們注入了ValidateCodeFilter,然后通過addFilterBefore方法將ValidateCodeFilter驗證碼校驗過濾器添加到了UsernamePasswordAuthenticationFilter前面。
v運行效果圖

其他參考/學(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圖形驗證碼的文章就介紹到這了,更多相關(guān)Spring Security驗證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Spring?Security配置多個數(shù)據(jù)源并添加登錄驗證碼的實例代碼
- Springboot+SpringSecurity實現(xiàn)圖片驗證碼登錄的示例
- Spring Security 實現(xiàn)多種登錄方式(常規(guī)方式外的郵件、手機驗證碼登錄)
- Spring Security添加驗證碼的兩種方式小結(jié)
- Spring Security 實現(xiàn)短信驗證碼登錄功能
- Spring Security登錄添加驗證碼的實現(xiàn)過程
- SpringBoot + SpringSecurity 短信驗證碼登錄功能實現(xiàn)
- SpringBoot結(jié)合SpringSecurity實現(xiàn)圖形驗證碼功能
- SpringBoot+Security 發(fā)送短信驗證碼的實現(xiàn)
- Spring Security OAuth2集成短信驗證碼登錄以及第三方登錄
- Spring Security 圖片驗證碼功能的實例代碼
相關(guān)文章
mybatis plus開發(fā)過程中遇到的問題記錄及解決
這篇文章主要介紹了mybatis plus開發(fā)過程中遇到的問題記錄及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
springboot配置過濾器和多個攔截器、執(zhí)行順序(案例詳解)
這篇文章主要介紹了springboot配置過濾器和多個攔截器、執(zhí)行順序,在文章開頭給大家介紹了過濾器配置的兩種方法,創(chuàng)建兩個攔截器,重寫方法結(jié)合實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-10-10
java Arrays.asList 返回什么與普通 ArrayList 區(qū)別介
Arrays.asList()返回一個固定大小的List視圖,而不是java.util.ArrayList,它不支持add和remove操作,但支持set操作,本文介紹java Arrays.asList返回什么與普通 ArrayList區(qū)別,感興趣的朋友跟隨小編一起看看吧2026-01-01
詳解JDBC的概念及獲取數(shù)據(jù)庫連接的5種方式
Java?DataBase?Connectivity是將Java與SQL結(jié)合且獨立于特定的數(shù)據(jù)庫系統(tǒng)的應(yīng)用程序編程接口,一種可用于執(zhí)行SQL語句的JavaAPI。本文主要介紹了JDBC的概念及獲取數(shù)據(jù)庫連接的5種方式,需要的可以參考一下2022-09-09
java中unicode和中文相互轉(zhuǎn)換的簡單實現(xiàn)
下面小編就為大家?guī)硪黄猨ava中unicode和中文相互轉(zhuǎn)換的簡單實現(xiàn)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08

