验证码服务

阅读更多

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

你可能感兴趣的:(java,验证码)