spring security로 로그인기능을 수행하는 와중에 궁금증이 생겼다.
- a123이라는 비밀번호를 암호화하면 같은 매번 같은 값으로 암호화가 되나?
- a123이라는 비밀번호와 암호화된 비밀번호의 일치여부는 어떻게 확인하지?
라는 궁금증이 생겼고 passwordEncoder class를 읽어보니 궁금증은 풀렸고 어느정도 개념이 자리잡히게 되었다.
정보처리기사 시험이 끝나면 스프링 프레임워크를 공부해야겠다........
끊임없이 공부해야하는 개발세계...........다들 화이팅!
본론으로 들어가서!
maven에 spring security 등록 등은 다 되어있는 상태에서 메서드만 불러오면 된다는 상황 가정.
@RequestMapping("user/registUser")
@ResponseBody
public ResponseEntity registUser(UserVO userVO,
HttpServletRequest request)
throws Exception {
HashMap<String, Object> map = new HashMap<String, Object>();
HttpStatus httpStatus;
String userPass = userVO.getUser_pswd();
if(userPass == null) {
map.put("message","password must be not null");
httpStatus = HttpStatus.BAD_REQUEST;
return new ResponseEntity<>(map, httpStatus);
}
log.info("암호화 전 : "+ userPass);
// 암호화
userPass = bcryptPasswordEncoder.encode(userPass);
log.info("암호화 후 : "+ userPass);
userVO.setUser_pswd(userPass);
try {
userService.insertUser(userVO);
httpStatus = HttpStatus.OK;
} catch (Exception e) {
map.put("error_type", "DataInsert");
map.put("error_message", e.getLocalizedMessage());
httpStatus = HttpStatus.BAD_REQUEST;
}
}
return new ResponseEntity<>(map, httpStatus);
}
@RequestMapping("user/loginChk")
@ResponseBody
public ResponseEntity userLoginChk( UserVO userVO
,HttpServletRequest request
,HttpServletResponse response
,HttpSession session) throws Exception{
HttpStatus httpStatus;
HashMap<String, Object> map = new HashMap<String, Object>();
String userPass = request.getParameter("user_pswd");
if(userPass == null) {
httpStatus = HttpStatus.BAD_REQUEST;
map.put("message","password must be not null");
log.info(map + " === " +httpStatus);
return new ResponseEntity<>(map, httpStatus);
}
// 아이디 확인
UserVO vo = userService.selectUserInfo(userVO);
httpStatus = HttpStatus.OK;
// true or false
log.info("pass chk : " +bcryptPasswordEncoder.matches(userPass,vo.getUser_pswd()) );
if(bcryptPasswordEncoder.matches(userPass,vo.getUser_pswd())) {
// 로그인 진행 (생략)
} else {
// 오류메세지 제공 (생략)
}
return new ResponseEntity<>(map,httpStatus);
}
💡 matches 메소드를 사용할 때 꼭! ~.matches(평문의 오리지널 패스워드, 암호화된 패스워드) 순으로 해야됨!!
이부분을 간과하고 넘어가서 어디서 잘못됬는지 찾느라 조금 고생했다.
왜 항상 가벼운 오타나 순서는 보이지 않느지 모르겠다.
혹시 잘못된 부분이있거나 해주실 말씀이 있다면 언제든 댓글 남겨주세요 😊