LoginController.java
일부
@RequestMapping("/auth/loginPage.do")
public ModelAndView loginPage(@RequestParam HashMap<String, String> params, HttpServletRequest req) {
ModelAndView mv = new ModelAndView();
mv.addObject("key", Calendar.getInstance().getTimeInMillis());
mv.addObject("loginForm", new JoinForm());
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (REMEBER_ME.equals(cookie.getName())) {
String memberId = cookie.getValue();
req.getSession().setAttribute(REMEBER_ME, memberId);
break;
}
}
}
mv.setViewName("auth/login");
return mv;
}
@PostMapping("/auth/login.do")
public String login(@Validated @ModelAttribute LoginForm loginForm, BindingResult bindingResult, HttpServletRequest req, HttpServletResponse resp) {
// (생략)
// 아이디 기억하기
if (loginForm.isRememberMe()) {
Cookie cookie = new Cookie(REMEBER_ME, loginForm.getMemberId());
cookie.setMaxAge(7 * 24 * 60 * 60); // 일주일
cookie.setHttpOnly(true);
resp.addCookie(cookie);
} else {
Cookie cookie = new Cookie(REMEBER_ME, null);
cookie.setMaxAge(0);
resp.addCookie(cookie);
}
// (생략)
return "redirect:/index.do";
}
cookie.setHttpOnly(true)
를 사용하는 이유HttpOnly
를 true
로 설정하면 클라이언트 측 스크립트가 쿠키에 접근할 수 없게 되어 크로스 사이트 스크립팅(XSS) 공격의 위험이 줄어듭니다.login.jsp
일부
<div class="login--form">
<div class="form-group">
<label for="user_name">Username</label>
<c:choose>
<c:when test="${empty sessionScope.rememberMe}">
<form:input
path="memberId"
id="user_name"
name="memberId"
type="text"
class="text_field"
placeholder="Enter your username..."
/>
</c:when>
<c:otherwise>
<!-- remeberMe의 저장된 id 값으로 대체 -->
<form:input
path="memberId"
id="user_name"
name="memberId"
type="text"
class="text_field"
value="${sessionScope.rememberMe}"
/>
</c:otherwise>
</c:choose>
<form:errors path="memberId" cssClass="error" />
</div>
<div class="form-group">
<label for="pass">Password</label>
<form:input
path="passwd"
id="pass"
name="passwd"
type="password"
class="text_field"
placeholder="Enter your password..."
/>
<form:errors path="passwd" cssClass="error" />
</div>
<div class="form-group">
<div class="custom_checkbox">
<!-- remeberMe에 값 저장 여부에 따라 체크 표시 결정 -->
<input type="checkbox" id="ch2" name="rememberMe" ${not empty
sessionScope.rememberMe ? checked : ''}>
<label for="ch2">
<span class="shadow_checkbox"></span>
<span class="label_text">Remember me</span>
</label>
</div>
</div>
</div>