인증 코드 서비스

3881 단어 자바인증번호
더 읽 기


	com.github.penggle
	kaptcha
	2.3.2


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.apache.commons.collections4.map.PassiveExpiringMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Kelvin  
 * @createDate 2018 11 15 
 */
@Service
public class CaptchaServiceImpl implements CaptchaService,InitializingBean {
    private Logger logger = LoggerFactory.getLogger(getClass());

    // msg
    final static String MSG_TIMEOUT = "      ";
    final static String MSG_FAILED = "       ";

    //config
    private int minutesToLive=3;
    private String imgFormat="png";

    private DefaultKaptcha producer;
    private Map captchaMap = Collections.synchronizedMap(
            new PassiveExpiringMap(minutesToLive,TimeUnit.MINUTES,new HashMap<>()));

    @Override
    public void afterPropertiesSet() {
        producer = new DefaultKaptcha();
        producer.setConfig(new Config(new Properties()));
    }

    @Override
    public String generateCaptchaKey() throws CaptchaException {
        String key = UUID.randomUUID().toString();
        captchaMap.put(key, producer.createText());
        return key;
    }

    @Override
    public byte[] generateCaptchaImage(String captchaKey) throws CaptchaException {
        String text = Optional.ofNullable(captchaMap.get(captchaKey))
                .orElseThrow(()->new CaptchaException(MSG_TIMEOUT));
        BufferedImage image = producer.createImage(text);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try{
            ImageIO.write(image, imgFormat, out);
        }catch(IOException e){
            logger.error(MSG_FAILED,e);
            throw new CaptchaException(MSG_FAILED,e);
        }
        return out.toByteArray();
    }

    @Override
    public boolean validateCaptcha(String captchaKey, String captchaValue) throws CaptchaException {
        if(Optional.ofNullable(captchaMap.get(captchaKey)).orElseThrow(()->new CaptchaException(MSG_TIMEOUT))
                .equalsIgnoreCase(captchaValue)){
            captchaMap.remove(captchaKey);
            return true;
        }
        return false;
    }
}


@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    final CaptchaService captchaService;

    public CaptchaController(CaptchaService captchaService) {
        this.captchaService = captchaService;
    }

    @GetMapping
    public ResponseEntity getImgCaptcha(){
        Map map= new HashMap();
        map.put("key", captchaService.generateCaptchaKey());
        map.put("img",  "data:image/png;base64,"+Base64.encodeBase64String(
                captchaService.generateCaptchaImage(map.get("key").toString())));
        return ResponseEntity.ok(map);
    }
}

좋은 웹페이지 즐겨찾기