天天看點

Spring Boot 整合 Spring Security(配置驗證碼)

Spring Boot 整合 Spring Security ,配置驗證碼。

1 建立工程

建立 Spring Boot 項目

spring-boot-springsecurity-verifycode

,添加

Web/Spring Security

依賴,如下:

Spring Boot 整合 Spring Security(配置驗證碼)

最終的依賴如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
           

2 準備驗證碼和接口

新增

VerifyCode

驗證碼生成工具類,如下:

// 生成驗證碼的工具類
public class VerifyCode {

    private int width = 100;// 生成驗證碼圖檔的寬度
    private int height = 50;// 生成驗證碼圖檔的高度
    private String[] fontNames = {"宋體", "楷體", "隸書", "微軟雅黑"};
    private Color bgColor = new Color(255, 255, 255);// 定義驗證碼圖檔的背景顔色為白色
    private Random random = new Random();
    private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private String text;// 記錄随機字元串

    /**
     * 擷取一個随意顔色
     *
     * @return
     */
    private Color randomColor() {
        int red = random.nextInt(150);
        int green = random.nextInt(150);
        int blue = random.nextInt(150);
        return new Color(red, green, blue);
    }

    /**
     * 擷取一個随機字型
     *
     * @return
     */
    private Font randomFont() {
        String name = fontNames[random.nextInt(fontNames.length)];
        int style = random.nextInt(4);
        int size = random.nextInt(5) + 24;
        return new Font(name, style, size);
    }

    /**
     * 擷取一個随機字元
     *
     * @return
     */
    private char randomChar() {
        return codes.charAt(random.nextInt(codes.length()));
    }

    /**
     * 建立一個空白的BufferedImage對象
     *
     * @return
     */
    private BufferedImage createImage() {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        g2.setColor(bgColor);// 設定驗證碼圖檔的背景顔色
        g2.fillRect(0, 0, width, height);
        return image;
    }

    public BufferedImage getImage() {
        BufferedImage image = createImage();
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            String s = randomChar() + "";
            sb.append(s);
            g2.setColor(randomColor());
            g2.setFont(randomFont());
            float x = i * width * 1.0f / 4;
            g2.drawString(s, x, height - 15);
        }
        this.text = sb.toString();
        drawLine(image);
        return image;
    }

    /**
     * 繪制幹擾線
     *
     * @param image
     */
    private void drawLine(BufferedImage image) {
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        int num = 5;
        for (int i = 0; i < num; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g2.setColor(randomColor());
            g2.setStroke(new BasicStroke(1.5f));
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    public String getText() {
        return text;
    }

    public static void output(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}
           

新增

VerifyCodeController

,提供驗證碼的擷取接口,如下:

@RestController
public class VerifyCodeController {
    @GetMapping("/vercode")
    public void code(HttpServletRequest req, HttpServletResponse resp, Model model) throws IOException {
        VerifyCode vc = new VerifyCode();
        BufferedImage image = vc.getImage();
        String text = vc.getText();
        model.addAttribute("text", text);
        System.out.println("text = " + text);
        HttpSession session = req.getSession();
        session.setAttribute("s_vercode", text);
        VerifyCode.output(image, resp.getOutputStream());
    }
}
           

resources/static

下新增

vercode.html

展示驗證碼,如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>測試驗證碼</title>
</head>
<body>
  <img src="/vercode" alt="">
</body>
</html>
           

通路 http://127.0.0.1:8080/vercode.html ,效果如下:

Spring Boot 整合 Spring Security(配置驗證碼)

3 配置驗證碼過濾器

新增

VerifyCodeFilter

驗證碼過濾器

// 驗證碼過濾器
@Component
public class VerifyCodeFilter extends GenericFilterBean {
    private String defaultFilterProcessUrl = "/doLogin";

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException, AuthenticationServiceException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
            // 驗證碼驗證
            String requestCaptcha = request.getParameter("vercode");
            String genCaptcha = (String) request.getSession().getAttribute("s_vercode");
            if (StringUtils.isEmpty(requestCaptcha) || StringUtils.isEmpty(genCaptcha))
                throw new AuthenticationServiceException("驗證碼不能為空!");
            if (!genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())) {
                throw new AuthenticationServiceException("驗證碼錯誤!");
            }
        }
        chain.doFilter(request, response);
    }
}
           

當請求方法是

POST

,并且請求位址是

/doLogin

時,擷取參數中的

vercode

字段值,該字段儲存了使用者從前端頁面傳來的驗證碼,然後擷取

session

中儲存的驗證碼,如果使用者沒有傳來驗證碼,則抛出“驗證碼不能為空”異常,如果使用者傳入了驗證碼,則判斷驗證碼是否正确,如果不正确則抛出“驗證碼錯誤”異常,否則執行

chain.doFilter(request, response);

使請求繼續向下走。

4 配置 Spring Security

新增

SecurityConfig

配置類,如下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    VerifyCodeFilter verifyCodeFilter; // 驗證碼過濾器

    @Bean
    PasswordEncoder passwordEncoder() {
        // return NoOpPasswordEncoder.getInstance();// 密碼不加密
        return new BCryptPasswordEncoder();// 密碼加密
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 在記憶體中配置2個使用者
        /*auth.inMemoryAuthentication()
                .withUser("admin").password("123456").roles("admin")
                .and()
                .withUser("user").password("123456").roles("user");// 密碼不加密*/

        auth.inMemoryAuthentication()
                .withUser("admin").password("$2a$10$fB2UU8iJmXsjpdk6T6hGMup8uNcJnOGwo2.QGR.e3qjIsdPYaS4LO").roles("admin")
                .and()
                .withUser("user").password("$2a$10$3TQ2HO/Xz1bVHw5nlfYTBON2TDJsQ0FMDwAS81uh7D.i9ax5DR46q").roles("user");// 密碼加密
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/doLogin")
                // 登入失敗的處理器(VerifyCodeFilter 抛出的異常不會到這裡?)
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 401);
                        map.put("msg", e.getMessage());
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                .csrf().disable();
                // 其他配置可參考 spring-boot-springsecurity-login
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 配置不需要攔截的請求位址,即該位址不走 Spring Security 過濾器鍊
        web.ignoring().antMatchers("/vercode");
        web.ignoring().antMatchers("/vercode.html");
    }
}
           

配置之後,在登入時就要求傳驗證碼了,如果不傳或傳錯,控制台就會抛出異常。

  • Spring Boot 教程合集(微信左下方閱讀全文可直達)。
  • Spring Boot 教程合集示例代碼:https://github.com/cxy35/spring-boot-samples
  • 本文示例代碼:https://github.com/cxy35/spring-boot-samples/tree/master/spring-boot-security/spring-boot-springsecurity-verifycode

掃碼關注微信公衆号 程式員35 ,擷取最新技術幹貨,暢聊 #程式員的35,35的程式員# 。獨立站點:https://cxy35.com

Spring Boot 整合 Spring Security(配置驗證碼)

繼續閱讀