最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring?Security圖形驗證碼的實現(xiàn)代碼

 更新時間:2024年10月15日 09:00:00   作者:請叫我頭頭哥  
本文介紹了如何在SpringSecurity自定義認(rèn)證中添加圖形驗證碼,首先需要在maven中添加相關(guān)依賴并創(chuàng)建驗證碼對象,然后通過Spring的HttpSessionSessionStrategy對象將驗證碼存儲到Session中,感興趣的朋友跟隨小編一起看看吧

生成圖形驗證碼

添加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í)資料:

v源碼地址

https://github.com/toutouge/javademosecond/tree/master/security-demo

到此這篇關(guān)于Spring Security圖形驗證碼的文章就介紹到這了,更多相關(guān)Spring Security驗證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • mybatis plus開發(fā)過程中遇到的問題記錄及解決

    mybatis plus開發(fā)過程中遇到的問題記錄及解決

    這篇文章主要介紹了mybatis plus開發(fā)過程中遇到的問題記錄及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • [Spring MVC] -簡單表單提交實例

    [Spring MVC] -簡單表單提交實例

    本篇文章主要介紹了[Spring MVC] -簡單表單提交實例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。
    2016-12-12
  • springboot配置過濾器和多個攔截器、執(zhí)行順序(案例詳解)

    springboot配置過濾器和多個攔截器、執(zhí)行順序(案例詳解)

    這篇文章主要介紹了springboot配置過濾器和多個攔截器、執(zhí)行順序,在文章開頭給大家介紹了過濾器配置的兩種方法,創(chuàng)建兩個攔截器,重寫方法結(jié)合實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2023-10-10
  • Spring深入分析容器接口作用

    Spring深入分析容器接口作用

    Spring內(nèi)部提供了很多表示Spring容器的接口和對象,我們今天來看看幾個比較常見的容器接口和具體的實現(xiàn)類,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • java Arrays.asList 返回什么與普通 ArrayList 區(qū)別介紹

    java Arrays.asList 返回什么與普通 ArrayList 區(qū)別介

    Arrays.asList()返回一個固定大小的List視圖,而不是java.util.ArrayList,它不支持add和remove操作,但支持set操作,本文介紹java Arrays.asList返回什么與普通 ArrayList區(qū)別,感興趣的朋友跟隨小編一起看看吧
    2026-01-01
  • 一篇文章帶你深入了解javaIO基礎(chǔ)

    一篇文章帶你深入了解javaIO基礎(chǔ)

    這篇文章主要介紹了java 基礎(chǔ)知識之IO總結(jié)的相關(guān)資料,Java中的I/O分為兩種類型,一種是順序讀取,一種是隨機讀取,需要的朋友可以參考下,希望對你有幫助
    2021-08-08
  • 詳解JDBC的概念及獲取數(shù)據(jù)庫連接的5種方式

    詳解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)

    java中unicode和中文相互轉(zhuǎn)換的簡單實現(xiàn)

    下面小編就為大家?guī)硪黄猨ava中unicode和中文相互轉(zhuǎn)換的簡單實現(xiàn)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-08-08
  • SpringBoot中的@PreAuthorize注解詳解

    SpringBoot中的@PreAuthorize注解詳解

    這篇文章主要介紹了SpringBoot中的@PreAuthorize注解詳解,@PreAuthorize注解會在方法執(zhí)行前進行權(quán)限驗證,支持Spring?EL表達式,它是基于方法注解的權(quán)限解決方案,需要的朋友可以參考下
    2023-09-09
  • 一文詳解Springboot中filter的原理與注冊

    一文詳解Springboot中filter的原理與注冊

    這篇文章主要為大家詳細(xì)介紹了Springboot中filter的原理與注冊的相關(guān)知識,文中的示例代碼講解詳細(xì),對我們掌握SpringBoot有一定的幫助,需要的可以參考一下
    2023-02-02

最新評論

炉霍县| 河北省| 措勤县| 平乐县| 平乐县| 定陶县| 永定县| 本溪市| 曲松县| 平江县| 三亚市| 闸北区| 新丰县| 新河县| 霍林郭勒市| 安义县| 凌云县| 汶川县| 乐陵市| 西乡县| 新昌县| 呼伦贝尔市| 会东县| 临武县| 承德市| 岑巩县| 诸城市| 南皮县| 越西县| 濉溪县| 祁连县| 昔阳县| 合江县| 米脂县| 凤城市| 镇坪县| 娄底市| 鄄城县| 海丰县| 石嘴山市| 冷水江市|