我有一个要求,让非认证用户填写一个表格,其中包含后端生成的验证码以提交批准,我使用Spring MVC和Cage生成验证码
@Controller
@Slf4j
public class ContactController {
@RequestMapping("/contact")
public String contact(Map<String, Object> model, HttpSession session, HttpServletRequest request) {
log.info("In contact");
try {
final String captchaCode = RandomStringUtils.randomAlphanumeric(5);
generate(new GCage(), 10, "cg1", ".jpg", captchaCode);
final File file = Paths.get("./cg13.jpg").toFile();
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
String base64String = new String(Base64.encodeBase64(bytes), "UTF-8");;
model.put("image", "data:image/jpeg;base64," + base64String);
model.put("captcha", captchaCode);
session.setAttribute("captcha", captchaCode);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return "contact";
}
@PostMapping("/check")
public String checkCaptcha(final Map<String, Object> model, HttpSession session) {
log.info("in check captcha");
final String captcha = (String) session.getAttribute("captcha");
return "contact";
}
在Thymeleaf,我正在使用
<img th:src="@{${image}}" />
<form th:action="@{/check}" th:object="${captcha}" method="post">
<input type="submit" />
</form>
为这样的非认证用户创建会话是一种不好的做法吗?那怎么办呢?
答案 0 :(得分:1)
没关系,但要注意session fixation。 Spring的会话处理通常非常好。当用户最终进行身份验证时,其默认配置将导致change of session ID。