1.背景
现在很多只进行简单的账号密码登录验证,其实是很容易被黑客攻击的。所以就出现了MFA(Multi-Factor Authentication),MFA验证也有很多方式,比如邮箱、短信、TOTP(Time-based One-Time Password)、生物验证等。
今天讲解一个最基础的邮箱验证。
2. 上代码逻辑
前端发送需要短信验证 -----》 后端随机生成一个6为的验证码并发送邮箱 ------》 建议放到reids设置一个有效时间 -------》 前端将验证码发送过来去redis取出进行校验。
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import javax.mail.internet.MimeMessage;
import java.util.Map;
@Component
@Slf4j
public class MailUtil {
@Autowired
private Configuration freeMarkerConfig;
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mfa.mail.from}")
private String from;
public void sendMail(String to,String subject, String content,
String templateName, Map<String, Object> model){
log.info("Entering sendMail() method, begin to send email [from:" + from + ", to:" + to + ", subject:" + subject + "]");
try{
if (templateName != null) {
Template template = freeMarkerConfig.getTemplate(templateName);
content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
}
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
if (to.contains(",") && to.contains("@")) {
String[] toMails = to.split(",");
message.setTo(toMails);
} else{
message.setTo(to);
}
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}catch (Exception e) {
log.error(ExceptionUtil.printStackTrace(e));
}
}
public void sendMimeMail(String to, String subject, String content, String templateName, Map<String, Object> model) {
log.info("Entering sendMimeMail() mfilePathethod, begin to send email [from:" + from + ", to:" + to + ", subject:" + subject + "]");
try { 前端发送需要短信验证 -----》 后端随机生成一个6为的验证码并发送邮箱 ------》 建议放到reids设置一个有效时间 -------》 前端将验证码发送过来去redis取出进行校验。
if (null != templateName) {
Template template = freeMarkerConfig.getTemplate(templateName);
content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
}
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
if (to.contains(",") && to.contains("@")) {
String[] toMails = to.split(",");
helper.setTo(toMails);
} else {
helper.setTo(to);
}
helper.setSubject(subject);
helper.setText(content,true);
/*FileSystemResource file = new FileSystemResource(filePath);
helper.addAttachment(Objects.requireNonNull(file.getFilename()), file);*/
mailSender.send(mimeMessage);
} catch (Exception e) {
log.error("send mail failed.:{}", e.getMessage());
}
}
}