- login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
const userInfo = {
username: null,
password: null
}
function login() {
userInfo.username = document.getElementById('username').value;
userInfo.password = document.getElementById('password').value;
console.log(userInfo.username);
console.log(userInfo.password);
$.ajax({
contentType : "application/json",
url: "/login",
type: "POST",
dataType:JSON,
data: JSON.stringify(userInfo),
}).done(function (res) {
window.sessionStorage.setItem("username", userInfo.username);
window.sessionStorage.setItem("nickname", res);
console.log(res.data.nickname);
console.log(res.data);
console.log(localStorage.getItem("nickname"));
})
.fail(function (res){
console.log(res);
});
}
</script>
<strong>아아디 : </strong>
<span><input id="username"></span>
<br/>
<strong>비밀번호 : </strong>
<span><input id="password"></span>
<P><input type="button" onclick="login()" value="로그인"></P>
</body>
</html>
ajax 통신 부분을 보면 응답 데이터 타입을 JSON으로 설정 해둔 상태로 로그인 요청을 보냈다. (dataType : JSON)
- AuthenticationFilter
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException {
System.out.println("successfulAuthentication 실행 - 인증이 완료 됨 시도중");
PrincipalDetails principalDetails = (PrincipalDetails) authResult.getPrincipal();
Cookie cookie = sessionManager.createSession(String.valueOf(principalDetails.getUserInfo().getId()));
response.addHeader("Access-Control-Allow-Origin","http://localhost:3000");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(principalDetails.getUserInfo().getNickname());
response.addCookie(cookie);
}
요청을 받는다면 커스텀한 스프링 필터에서 스프링 시큐리티의 UsernamePasswordAuthentication을 통해 유저 정보 검사를 하고 인증완료 되고 successfulAuthentication 메서드 부분에서 응답 처리를 해주게 되는데 자세히 응답 코드를 보면 여기에도 CotentType을 JSON으로 응답하게 설정해뒀었다..
그래서 ajax의 done이 작동을 하지 않았던 것이다.
이 에러를 굉장히 늦게 알았다 왜냐하면 httpStatusCode는 200으로 응답은 정상적으로 받아져서 에러가 난줄 모르고있었다..
클라이언트 부분에서도 로그인 처리를 위해 sessionStorage에 유저정보를 담기 위해서 하던 도중에 알게 됐다..
- 수정된 login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
const userInfo = {
username: null,
password: null
}
function login() {
userInfo.username = document.getElementById('username').value;
userInfo.password = document.getElementById('password').value;
console.log(userInfo.username);
console.log(userInfo.password);
$.ajax({
contentType : "application/json",
url: "/login",
type: "POST",
data: JSON.stringify(userInfo),
}).done(function (res) {
window.sessionStorage.setItem("username", userInfo.username);
window.sessionStorage.setItem("nickname", res);
console.log(res);
console.log(res.data);
console.log(localStorage.getItem("nickname"));
})
.fail(function (res){
console.log(res);
});
}
</script>
<strong>아아디 : </strong>
<span><input id="username"></span>
<br/>
<strong>비밀번호 : </strong>
<span><input id="password"></span>
<P><input type="button" onclick="login()" value="로그인"></P>
</body>
</html>
dataType의 JSON을 지워준다.
- 수정된 필터
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException {
System.out.println("successfulAuthentication 실행 - 인증이 완료 됨 시도중");
PrincipalDetails principalDetails = (PrincipalDetails) authResult.getPrincipal();
Cookie cookie = sessionManager.createSession(String.valueOf(principalDetails.getUserInfo().getId()));
response.addHeader("Access-Control-Allow-Origin","http://localhost:3000");
// response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(principalDetails.getUserInfo().getNickname());
response.addCookie(cookie);
}
마찬가지로 response.setContentType구문을 주석처리 해주면
세션스토리지와 콘솔에 제대로 값이 들어가는 것을 확인할 수 있다.
'JAVA' 카테고리의 다른 글
Spring Boot 회원정보 출력 (2) 비동기 통신 Ajax (0) | 2022.09.15 |
---|---|
Spring Boot 회원정보 출력 (1) 비동기 통신 Ajax (0) | 2022.09.15 |
Spring Boot 게시판 및 댓글 출력 (thymeleaf, ajax) JPA 양방향 매핑 (0) | 2022.09.06 |
Spring Boot, thymeleaf ajax로그인 요청 (javascript) (0) | 2022.09.03 |
Spring Boot 게시판 상세내용 조회 구현 (0) | 2022.08.31 |
댓글