2017-09-19 4 views
0

私は承認を提出するためにキャプチャを生成し、バックエンドを含んでいるフォームに必要事項を記入非認証されたユーザーを持って、要件を持って、私はThymeleaf Iでキャプチャに認証されていないユーザーにセッションを使用する必要がありますか?

@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"; 
    } 

を生成するために、Spring MVCのとケージを使用しています'を使用して

<img th:src="@{${image}}" /> 

<form th:action="@{/check}" th:object="${captcha}" method="post"> 
    <input type="submit" /> 
</form> 

このような認証されていないユーザーのセッションを作成するのは悪い習慣ですか?それ以外はどのように処理できますか?

答えて

1

いいですが、session fixationにご注意ください。 Springのセッション処理は一般にかなり良いです。デフォルト設定では、ユーザーが最終的に認証されるときにはchange of session IDになります。

+0

この場合、認証されたユーザーと認証されていないユーザーを区別することはできますか?両方にHttpSessionオブジェクトがある場合はどうなりますか?ショッピングカートのためにsay –

+0

Springは認証状態を追跡するためにセッションに 'SecurityContext'を保持します。一部のドキュメント[こちら](https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/technical-overview.html#securitycontextholder-securitycontext-and-authentication-objects) – teppic

関連する問題