五、SpringSecurity圖片驗證碼

一对扶、開發(fā)生成圖形驗證碼接口

1.根據(jù)隨機數(shù)生成圖片

因為不管是手機APP還是瀏覽器都可能會用到,所以我寫到了core模塊惭缰。

2.將隨機數(shù)存到Session中
3.再將生成的圖片寫到接口的響應(yīng)中

首先定義一個實體類,封裝驗證碼的信息笼才,其中包含圖片信息漱受,驗證碼,以及過期時間

package com.tinner.security.core.validate.code;

import java.awt.image.BufferedImage;
import java.time.LocalDateTime;

public class ImageCode {

    private BufferedImage image;

    private String code;

    private LocalDateTime expireTime;

    public ImageCode(BufferedImage image, String code, int expireTime) {
        this.image = image;
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expireTime);
    }

    public boolean isExpried(){
        return LocalDateTime.now().isAfter(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;
    }
}

注意:在重寫構(gòu)造方法的時候骡送,入?yún)⑹且粋€int類型的一個過期時間昂羡,就是一個秒,一般過期時間都是60秒摔踱,然后在構(gòu)造方法里面 this.expireTime = LocalDateTime.now().plusSeconds(expireTime);這個代碼指的是將過期時間設(shè)為一個未來的一個時間虐先。這個類中還有一個判斷驗證碼是否過期的一個方法isExpried。
代碼如下


@RestController
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);
        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, x + xl, y + 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();

        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);
    }

}

二派敷、在認(rèn)證流程中加入圖形驗證碼的校驗

在SpringSecurity并沒有提供圖像驗證碼的過濾器蛹批,但是我們可以在過濾器鏈中加入我們自己寫的圖形過濾器。就是在UsernamePasswordAuthenticationFilter過濾器之前加一個自己寫的過濾器篮愉。在自己寫的過濾器里面去執(zhí)行校驗的邏輯腐芍,如果驗證通過則將請求通過,如果驗證失敗就拋出異常试躏。
代碼:

package com.tinner.security.core.validate.code;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ValidateCodeFilter extends OncePerRequestFilter {

    public AuthenticationFailureHandler getAuthenticationFailureHandler() {
        return authenticationFailureHandler;
    }

    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    private AuthenticationFailureHandler authenticationFailureHandler;

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if (StringUtils.equals("/authentication/form",httpServletRequest.getRequestURI()) && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(),"post")){
            try {
                validate(new ServletWebRequest(httpServletRequest));
            }catch (ValidateCodeException e){
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                return ;
            }
        }

        filterChain.doFilter(httpServletRequest,httpServletResponse);

    }

    /**
     * 校驗邏輯
     * @param
     */
    public 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 class ValidateCodeException extends AuthenticationException {

    public ValidateCodeException(String msg) {
        super(msg);
    }

    private static final long serialVersionUID = 1422465195260228715L;
}

我來繼承了AuthenticationException 猪勇,這個異常是安全框架默認(rèn)提供的一個異常。
然后是重寫頁面index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登錄</title>
</head>
<body>
    <h1>標(biāo)準(zhǔn)登錄頁面</h1>
    <h3>表單登錄</h3>
        <form action="/authentication/form" method="post">
            <table>
                <tr>
                    <td>用戶名:</td>
                    <td><input type="text" name="username"/></td>
                </tr>
                <tr>
                    <td>密碼:</td>
                    <td><input type="password" name="password"/></td>
                </tr>
                <tr>
                    <td>驗證碼:</td>
                    <td>
                        <input type="text" name="imageCode"/>
                        <img src="/code/image">
                    </td>
                </tr>
                <tr>
                    <td colspan="2"><button type="submit">登錄</button></td>
                </tr>
            </table>
        </form>

</body>
</html>

三颠蕴、配置SpringSecurity的config

package com.tinner.security.browser;

import com.tinner.security.core.properties.SecurityProperties;
import com.tinner.security.core.validate.code.ValidateCodeController;
import com.tinner.security.core.validate.code.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.File;

/**
 * WebSecurityConfigurerAdapter是springSecurity提供的一個適配器類
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private AuthenticationSuccessHandler tinnerAuthentivationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler tinnerAuthentivationFailureHandler;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
        validateCodeFilter.setAuthenticationFailureHandler(tinnerAuthentivationFailureHandler);
//        super.configure(http);
        //實現(xiàn)的效果:讓它去表單登錄泣刹,而不是alert框
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                .formLogin()
                .loginPage("/authentication/require")
                .loginProcessingUrl("/authentication/form")
                .successHandler(tinnerAuthentivationSuccessHandler)
                .failureHandler(tinnerAuthentivationFailureHandler)
//        http.httpBasic()
                .and()
                .authorizeRequests()//對請求進行授權(quán)
                .antMatchers("/authentication/require",securityProperties.getBrowser().getLoginPage(),"/code/image").permitAll()
                .anyRequest()//任何請求
                .authenticated()
        .and().csrf().disable();//都需要身份認(rèn)證

    }
}

這樣助析,項目就可以運行了,但是在我登錄失敗之后它會彈出堆棧信息椅您,并不能顯示出我的校驗的信息外冀。因此我還得重寫我之前的TinnerAuthentivationFailureHandler的onAuthenticationFailure方法,之前是將異常全部寫入httpServletResponse中襟沮,現(xiàn)在只將異常的message寫進 去即可

package com.tinner.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tinner.security.browser.support.SimpleResponse;
import com.tinner.security.core.properties.LoginType;
import com.tinner.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("tinnerAuthentivationFailureHandler")
//public class TinnerAuthentivationFailureHandler implements AuthenticationFailureHandler {

public class TinnerAuthentivationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        LOGGER.info("登錄失敗");
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
            httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(e.getMessage())));
        }else{
            super.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
        }

    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末锥惋,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子开伏,更是在濱河造成了極大的恐慌膀跌,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件固灵,死亡現(xiàn)場離奇詭異捅伤,居然都是意外死亡,警方通過查閱死者的電腦和手機巫玻,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進店門丛忆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人仍秤,你說我怎么就攤上這事熄诡。” “怎么了诗力?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵凰浮,是天一觀的道長。 經(jīng)常有香客問我苇本,道長袜茧,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任瓣窄,我火速辦了婚禮笛厦,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘俺夕。我一直安慰自己裳凸,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布劝贸。 她就那樣靜靜地躺著登舞,像睡著了一般。 火紅的嫁衣襯著肌膚如雪悬荣。 梳的紋絲不亂的頭發(fā)上菠秒,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天,我揣著相機與錄音,去河邊找鬼践叠。 笑死言缤,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的禁灼。 我是一名探鬼主播管挟,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼弄捕!你這毒婦竟也來了僻孝?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤守谓,失蹤者是張志新(化名)和其女友劉穎穿铆,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體斋荞,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡荞雏,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了平酿。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片凤优。...
    茶點故事閱讀 40,498評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖蜈彼,靈堂內(nèi)的尸體忽然破棺而出筑辨,到底是詐尸還是另有隱情,我是刑警寧澤幸逆,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布挖垛,位于F島的核電站,受9級特大地震影響秉颗,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜送矩,卻給世界環(huán)境...
    茶點故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一蚕甥、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧栋荸,春花似錦菇怀、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽匆背。三九已至呼伸,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背括享。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工搂根, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人铃辖。 一個月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓剩愧,卻偏偏與公主長得像,于是被迫代替她去往敵國和親娇斩。 傳聞我的和親對象是個殘疾皇子仁卷,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,507評論 2 359

推薦閱讀更多精彩內(nèi)容