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

SpringSecurity實現圖形驗證碼功能的實例代碼

 更新時間:2020年05月20日 14:29:07   作者:天天丶  
Spring Security 的前身是 Acegi Security ,是 Spring 項目組中用來提供安全認證服務的框架。這篇文章主要介紹了SpringSecurity實現圖形驗證碼功能,需要的朋友可以參考下

Spring Security

Spring Security是一個能夠為基于Spring的企業(yè)應用系統提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組可以在Spring應用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反轉Inversion of Control ,DI:Dependency Injection 依賴注入)和AOP(面向切面編程)功能,為應用系統提供聲明式的安全訪問控制功能,減少了為企業(yè)系統安全控制編寫大量重復代碼的工作。

Spring Security

下載:https://github.com/whyalwaysmea/Spring-Security

本文重點給大家介紹SpringSecurity實現圖形驗證碼功能,具體內容如下:

1.開發(fā)生成圖形驗證碼接口

-> 封裝ImageCode對象,來存放圖片驗證碼的內容、圖片以及有效時間

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;
 // 出入一個秒數,自動轉為時間,如過期時間為60s,這里的expireIn就是60,轉換為當前時間上加上這個秒數
 this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
 }
 public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {
 this.image = image;
 this.code = code;
 this.expireTime = expireTime;
 }
 public BufferedImage getImage() {
 return image;
 }
 public void setImage(BufferedImage image) {
 this.image = image;
 }
 public String getCode() {
 return code;
 }
 public void setCode(String code) {
 this.code = code;
 }
 public LocalDateTime getExpireTime() {
 return expireTime;
 }
 public void setExpireTime(LocalDateTime expireTime) {
 this.expireTime = expireTime;
 }
}

-> 寫一個Controller用于生成圖片和校驗驗證碼

public class ValidateCodeController {
 private static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
 private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
 @GetMapping("/code/image")
 public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
 // 根據隨機數生成圖片
 ImageCode imageCode = createImageCode(request);
 // 將隨機數存到session中
 sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
 // 將生成的圖片寫到接口的響應中
 ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
 }

 private ImageCode createImageCode(HttpServletRequest request) {
 // 圖片的寬高(像素)
 int width = 67;
 int height = 23;
 // 生成圖片對象
 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
 
 Graphics g = image.getGraphics();
 // 生成隨機條紋干擾
 Random random = new Random();
 g.setColor(getRandColor(200, 250));
 g.fillRect(0, 0, width, height);
 g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
 g.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);
 g.drawLine(x, y, xl, yl);
 }
 
 // 生成四位隨機數
 String sRand = "";
 for (int i = 0; i < 4; i++) {
 String rand = String.valueOf(random.nextInt(10));
 sRand += rand;
 g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
 g.drawString(rand, 13 * i + 6, 16);
 }
 g.dispose();
 // 60秒有效
 return new ImageCode(image, sRand, 60);
 }

 /**
 * 生成隨機背景條紋
 * @param fc
 * @param bc
 * @return
 */
 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);
 }
}

第一步:根據隨機數生成圖片

ImageCode imageCode = createImageCode(request);

第二步:將隨機數存到session中

sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);

第三步:將生成的圖片寫到接口的響應中

ImageIO.write(imageCode.getImage(), “JPEG”, response.getOutputStream());

-> 在靜態(tài)頁面中加入圖片驗證碼的標簽

<tr>
 <td>圖形驗證碼:</td>
 <td>
 <input type="text" name="imageCode">
 <img src="/code/image">
 </td>
</tr>

-> 將接口請求地址配進認證

@Override
protected void configure(HttpSecurity http) throws Exception {
 http.formLogin()
 .loginPage("/authencation/require")
 .loginProcessingUrl("/authentication/form")
 .successHandler(imoocAuthenticationSuccessHandler)
 .failureHandler(imoocAuthenticationFailureHandler)
 .and()
 .authorizeRequests()
 .antMatchers("/authencation/require", 
 securityPropertis.getBrowserPropertis().getLoginPage(),
 "/code/image").permitAll() // 加入"/code/image"地址
 .anyRequest()
 .authenticated()
 .and()
 .csrf().disable();
}

->啟動服務器訪問靜態(tài)表單

如圖所示:

圖片驗證碼

2.在認證流程中加入圖形驗證碼校驗

-> 寫一個filter進行攔截
public class ValidateCodeFilter extends OncePerRequestFilter{
 private AuthenticationFailureHandler authenticationFailureHandler;
 private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
 @Override
 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
 throws ServletException, IOException {
 //如果訪問的是/authentication/form并且為post請求
 if(StringUtils.equals("/authentication/form", request.getRequestURI())
 && StringUtils.equals(request.getMethod(), "post")) {
 try {
 // 驗證圖片驗證碼是否填寫正確
 validate(new ServletWebRequest(request));
 } catch (ValidateCodeException e) {
 // 拋出異常,并返回,不再訪問資源
 authenticationFailureHandler.onAuthenticationFailure(request, response, e);
 return;
 }
 }
 // 通過,執(zhí)行后面的filter
 filterChain.doFilter(request, response);
 }
 // 校驗驗證碼的邏輯
 private void validate(ServletWebRequest request) throws ServletRequestBindingException {
 ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request, ValidateCodeController.SESSION_KEY);
 String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "imageCode");
 if(StringUtils.isBlank(codeInRequest)) {
 throw new ValidateCodeException("驗證碼的值不能為空");
 }
 if(codeInSession == null){
 throw new ValidateCodeException("驗證碼不存在");
 }
 if(codeInSession.isExpried()) {
 sessionStrategy.removeAttribute(request, ValidateCodeController.SESSION_KEY);
 throw new ValidateCodeException("驗證碼已過期");
 }
 if(!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
 throw new ValidateCodeException("驗證碼不匹配");
 }
 sessionStrategy.removeAttribute(request, ValidateCodeController.SESSION_KEY);
 }
 public AuthenticationFailureHandler getAuthenticationFailureHandler() {
 return authenticationFailureHandler;
 }
 public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
 this.authenticationFailureHandler = authenticationFailureHandler;
 }
 public SessionStrategy getSessionStrategy() {
 return sessionStrategy;
 }
 public void setSessionStrategy(SessionStrategy sessionStrategy) {
 this.sessionStrategy = sessionStrategy;
 }
}

-> 配置再configure中,生效

@Override
protected void configure(HttpSecurity http) throws Exception {
 // 聲明filter
 ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
 // 配置驗證失敗執(zhí)行的handler
 validateCodeFilter.setAuthenticationFailureHandler(imoocAuthenticationFailureHandler);
 // 添加filter到認證流程
 http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
 .formLogin()
 .loginPage("/authencation/require")
 .loginProcessingUrl("/authentication/form")
 .successHandler(imoocAuthenticationSuccessHandler)
 .failureHandler(imoocAuthenticationFailureHandler)
 .and()
 .authorizeRequests()
 .antMatchers("/authencation/require", 
 securityPropertis.getBrowserPropertis().getLoginPage(),
 "/code/image").permitAll()
 .anyRequest()
 .authenticated()
 .and()
 .csrf().disable();
}

至此,圖片驗證碼驗證流程已經全部完成。

啟動服務,進行測試即可。

總結

到此這篇關于SpringSecurity實現圖形驗證碼功能的實例代碼的文章就介紹到這了,更多相關SpringSecurity圖形驗證碼內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • RocketMQ之Consumer整體介紹啟動源碼分析

    RocketMQ之Consumer整體介紹啟動源碼分析

    這篇文章主要為大家介紹了RocketMQ源碼分析之Consumer整體介紹啟動分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-05-05
  • Spring事務管理配置文件問題排查

    Spring事務管理配置文件問題排查

    這篇文章主要介紹了Spring事務管理配置文件問題排查,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-05-05
  • java并發(fā)編程StampedLock高性能讀寫鎖詳解

    java并發(fā)編程StampedLock高性能讀寫鎖詳解

    這篇文章主要為大家介紹了java并發(fā)編程StampedLock高性能讀寫鎖的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-05-05
  • java如何完成輸出語句實例詳解

    java如何完成輸出語句實例詳解

    輸入輸出可以說是計算機的基本功能,下面這篇文章主要給大家介紹了關于java如何完成輸出語句的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-01-01
  • IDEA遠程部署調試Java應用程序的詳細流程

    IDEA遠程部署調試Java應用程序的詳細流程

    這篇文章主要介紹了IDEA遠程部署調試Java應用程序,本文通過圖文并茂的形式給大家介紹的非常詳細,需要的朋友可以參考下
    2021-10-10
  • MyBatis-Plus通用CRUD操作的實現

    MyBatis-Plus通用CRUD操作的實現

    MyBatis-Plus是基于MyBatis的增強工具,主要目的是簡化MyBatis的使用并提升開發(fā)效率,它提供了通可以用CRUD操作、分頁插件、多種插件支持、自動代碼生成器等功能,感興趣的可以了解一下
    2024-10-10
  • Java構造方法有什么作用?

    Java構造方法有什么作用?

    在本篇文章里小編給大家介紹了關于Java構造方法的作用以及相關的基礎知識點,對此有需要的朋友們可以跟著學習下。
    2022-11-11
  • Java元注解Retention代碼示例介紹

    Java元注解Retention代碼示例介紹

    注解@Retention可以用來修飾注解,是注解的注解,稱為元注解。Retention注解有一個屬性value,是RetentionPolicy類型的,Enum?RetentionPolicy是一個枚舉類型,這個枚舉決定了Retention注解應該如何去保持,也可理解為Rentention?搭配?RententionPolicy使用
    2022-08-08
  • 關于SpringBoot中controller參數校驗的使用

    關于SpringBoot中controller參數校驗的使用

    本文主要介紹了關于SpringBoot中controller參數校驗的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-01-01
  • flink進階富函數生命周期介紹

    flink進階富函數生命周期介紹

    這篇文章主要為大家介紹了flink進階富函數生命周期的舉例介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03

最新評論

五寨县| 西丰县| 新巴尔虎左旗| 鲁山县| 永顺县| 灵宝市| 克拉玛依市| 禄劝| 敦煌市| 尼勒克县| 兴山县| 无棣县| 凉山| 泰宁县| 扎囊县| 库尔勒市| 临湘市| 呼图壁县| 石景山区| 海宁市| 元阳县| 江口县| 旌德县| 噶尔县| 静安区| 奈曼旗| 三原县| 奉化市| 曲麻莱县| 绿春县| 永吉县| 资源县| 利川市| 慈溪市| 泗水县| 高碑店市| 日照市| 射洪县| 成武县| 历史| 溧水县|