고래씌

[Spring] 2-2. 회원가입 페이지, 비밀번호 암호화 저장 본문

Server/Spring

[Spring] 2-2. 회원가입 페이지, 비밀번호 암호화 저장

고래씌 2024. 1. 22. 17:06

1. 회원가입

 

- WEB-INF/views/member 폴더 아래에 memmberErollForm.jsp 추가

▶ memberErollForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
	.outer{
	        background:black;
	        color:white;
	        width:1000px;
	        margin:auto;
	        margin-top:50px;
	}
	#enroll-form table {margin:auto;}
	#enroll-form input {margin:5px;}
</style>
</head>
<body>
	<jsp:include page="/WEB-INF/views/common/header.jsp"></jsp:include>
	
	
	<div class="outer">
        <br>
        <h2 align="center">회원가입</h2>
        <form id="enroll-form" action="<%=request.getContextPath() %>/insert.me" method="post">
            <!-- 회원가입form안에.txt -->
            <table align="center">
                <tr>
                    <td>* ID</td>
                    <td><input type="text" name="userId" required>
                        <button type="button" onclick="idCheck();">아이디중복체크</button>
                    </td>
                </tr>
                <tr>
                    <td>* PWD</td>
                    <td><input type="password" name="userPwd" required></td>
                </tr>
                <tr>
                    <td>* NAME</td>
                    <td><input type="text" name="userName" required></td>
                </tr>
                <tr>
                    <td>&nbsp;&nbsp;EMAIL</td>
                    <td><input type="email" name="email"></td>
                </tr>
                <tr>
                    <td>&nbsp;&nbsp;BIRTHDAY</td>
                    <td><input type="text" name="birthday" placeholder="생년월일(6자리)"></td>
                </tr>
                <tr>
                    <td>&nbsp;&nbsp;GENDER</td>
                    <td align="center">
                        <input type="radio" name="gender" value="M" checked> 남
                        <input type="radio" name="gender" value="F"> 여
                    </td>
                </tr>
                <tr>
                    <td>&nbsp;&nbsp;PHONE</td>
                    <td><input type="text" name="phone" placeholder="-포함"></td>
                </tr>
                <tr>
                    <td>&nbsp;&nbsp;ADDRESS</td>
                    <td><input type="text" name="address"></td>
                </tr>
            </table>
            <br>
            <div align="center">
                <button type="reset">초기화</button>
                <button type="submit">회원가입</button>
            </div>
        </form>
    </div>
	
	<jsp:include page="/WEB-INF/views/common/footer.jsp"></jsp:include>

</body>
</html>

 

 

▶ MemberController.java

=> get 방식

	@GetMapping("/insert.me")
	public String memberEroll(HttpSession session) {
		
		return "member/memberErollForm";
	}

 

=> (WEB-INF/views)member폴더 안에 있는 memberErollForm으로 서블렛 보냄

 

=> post방식

=> Member m을 넣으면 알아서 spring부트가 name값을 찾아서 Member객체에 값을 담아줌.

	@PostMapping("/insert.me")
	public String memberInsert(Member m, HttpSession session, Model model) {
		
		
		int result = mService.insertMember(m);
		
		String url = "";
		
		if(result > 0) {
			session.setAttribute("alertMsg", "회원가입성공");
			url = "redirect:/";
		}else {
			model.addAttribute("errorMsg", "회원가입실패");
			url = "common/errorPage";
		}
		
		return url;
	}

 

 

▶ MemberService.java

int insertMember(Member m);

 

 

▶ MemberServiceImpl.java

@Override
public int insertMember(Member m) {
    return memberDao.insertMember(m);
}

 

 

▶MemberDao.java

int insertMember(Member m);

 

 

▶ MemberDaoImpl.java

@Override
public int insertMember(Member m) {
    return sqlSession.insert("memberMapper.insertMember", m);
}

 

 

▶ member-mapper.xml

	<insert id="insertMember" parameterType="member">
		INSERT INTO MEMBER VALUES(
				SEQ_UNO.NEXTVAL,
				#{userId},
				#{userPwd},
				#{userName},
				#{email},
				#{birthday},
				#{gender},
				#{phone},
				#{address},
				DEFAULT,
				DEFAULT,
				DEFAULT
			)
	</insert>

 

 

 

 


2. 회원가입 비밀번호 암호화 저장

■ BCrypt방식의 암호화 사용해보기

1) spring-security 의존성 추가

 

① 메이븐 레파지토리 접속

 

 

▶ pom.xml

=> 빨간밑줄 추가하고 아래에 security 3가지 모두 추가

 

		<!-- spring -security -->
		<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
		<dependency>
		    <groupId>org.springframework.security</groupId>
		    <artifactId>spring-security-core</artifactId>
		    <version>${org.springframework.security-version}</version>
		</dependency>
		
		<!-- spring -security Web -->
		<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
		<dependency>
		    <groupId>org.springframework.security</groupId>
		    <artifactId>spring-security-web</artifactId>
		    <version>${org.springframework.security-version}</version>
		</dependency>
		
		<!-- spring -security Config -->
		<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
		<dependency>
		    <groupId>org.springframework.security</groupId>
		    <artifactId>spring-security-config</artifactId>
		    <version>${org.springframework.security-version}</version>
		</dependency>

 

 

 

2) Bcrypt...Encoder클래스 bean객체로 등록

WEB-INF 폴더 아래 spring 폴더에 "security-context.xml" 파일 생성

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- 2)빈 객체로 등록 완료 -->
	<bean id="bCryptPasswordEncoder"
		  class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
</beans>

 

 

 

3) web.xml에 2번과정에서 생성한 xml파일을 로딩할 수 있도록 추가

▶ web.xml

 

 

 

4) MemberContoller.java

▶ MemberController.java

 

	@PostMapping("/insert.me")
	public String memberInsert(Member m, HttpSession session, Model model) {
		
		/*
		 * BCrypt방식의 암호화 사용해보기
		 * 1) spring-security 의존성 추가
		 * 2) Bcrypt...Encoder클래스 bean객체로 등록
		 * 3) web.xml에 2번과정에서 생성한 xml파일을 로딩할 수 있도록 추가
		 */
		
		// 암호화작업
		String encPwd = bCryptPasswordEncoder.encode(m.getUserPwd());
		m.setUserPwd(encPwd); // 암호화된 pwd로 변경
		
		int result = mService.insertMember(m);
		
		String url = "";
		
		if(result > 0) {
			session.setAttribute("alertMsg", "회원가입성공");
			url = "redirect:/";
		}else {
			model.addAttribute("errorMsg", "회원가입실패");
			url = "common/errorPage";
		}
		
		return url;
	}

 

 

=> 암호화 후 로그인 요청 처리

Member loginUser = mService.loginMember(m.getUserId());

☞ loginUser의 userPwd는 암호화처리된 비밀번호가 담겨있음
m 안에는 암호화 전 평문형태의 비밀번호가 담겨있음

 

☞ Bcry.. matches메소드 사용!!!

matches(평문, 암호문)을 작성시 내부적으로 두 값이 일치하는지 검사후 일치하면 true / 일치하지 않으면 false

	@PostMapping("login.me")
	public ModelAndView loginMember(@ModelAttribute Member m, HttpSession session, Model model, ModelAndView mv) {
		
		// 암호화 전 로그인 요청 처리
//		Member loginUser = mService.loginMember(m);
		
		// 암호화 후 로그인 요청 처리
		Member loginUser = mService.loginMember(m.getUserId());

		if(loginUser != null && bCryptPasswordEncoder.matches(m.getUserPwd(), loginUser.getUserPwd())) { // 로그인 성공
			model.addAttribute("loginUser", loginUser);
//			session.setAttribute("loginUser", loginUser);
			mv.setViewName("redirect:/");
		}else {  // 로그인 실패시

			mv.addObject("errorMsg", "오류발생");
			mv.setViewName("common/errorPage");
		}
		return mv;
	}

 

 

▶ MemberService, MemberServiceImpl, MemberDao, MemberDaoImpl, memberMapper 모두 변경