본문 바로가기
개발/Spring

[SpringBoot] Session을 이용한 로그인 , 인증 하기

by 코딩하는 흰둥이 2023. 4. 26.

이전글 https://greed-yb.tistory.com/219

[Spring] Bootstrap 적용 웹 게시판 만들기 - 회원가입

이전글 https://greed-yb.tistory.com/216 [SpringBoot+IntelliJ+Oracle+Thymeleaf+Paging] 웹 게시판 만들기(8) - 실행 이전글 https://greed-yb.tistory.com/215 [SpringBoot+IntelliJ+Oracle+Thymeleaf+Paging] 웹 게시판 만들기(7) - html 화면

greed-yb.tistory.com

 
 

Controller
  • MainController
    /**
     * 메인 페이지
     * @return
     * @throws Exception
     */
    @GetMapping("/")
    public String Main(Model model, HttpSession session) throws Exception{

	// session 확인
        String user = (String) session.getAttribute("user");
        if(user == null){
            return "login";
        }else {
            return "index";

        }
}

localhost:9090 접속 시 session 을 조회하고 없으면 login page , 있으면 index page 로 이동한다
 
 

  • LoginController
@Controller
public class LoginController {

    @Autowired
    private MemberService memberService;


    /**
     * 로그인 페이지
     * @return
     * @throws Exception
     */
    @GetMapping("/login")
    public String login() throws Exception {
        return "login";
    }

    /**
     * 로그인
     * @param model
     * @param m_id
     * @param m_password
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    public String login(Model model, String m_id, String m_password, HttpSession session) throws Exception{

        MemberVo vo = memberService.selectMember(m_id);
        String url = "login";

        if (vo == null) {
            model.addAttribute("messageId", "아이디가 틀렸습니다");
        } else if (!vo.getM_password().equals(m_password)) {
            model.addAttribute("messagePwd", "비밀번호가 틀렸습니다");
        } else {
            session.setAttribute("user" , m_id);
            url = "index";
        }
        return url;
    }

    /**
     * 로그아웃
     * @param request
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping("/logout")
    public String logout(HttpServletRequest request , HttpSession session) throws Exception{
        session = request.getSession();
        session.invalidate();

        return "redirect:/";
    }
}

로그아웃 시 HttpSession session 만 명시해서 session.invalidate(); 만으로도 세션을 지울 수 있다
 
 
 

login.html
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>SB Admin 2 - Login</title>

    <!-- Custom fonts for this template-->
    <link href="../bootstrap/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link
        href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
        rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="../bootstrap/css/sb-admin-2.min.css" rel="stylesheet">

</head>

<body class="bg-gradient-primary">

    <div class="container">

        <!-- Outer Row -->
        <div class="row justify-content-center">

            <div class="col-xl-10 col-lg-12 col-md-9">

                <div class="card o-hidden border-0 shadow-lg my-5">
                    <div class="card-body p-0">
                        <!-- Nested Row within Card Body -->
                        <div class="row">
                            <div class="col-lg-6 d-none d-lg-block bg-login-image"></div>
                            <div class="col-lg-6">
                                <div class="p-5">
                                    <div class="text-center">
                                        <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1>
                                    </div>
                                    <form class="user" method="post" th:action="@{/login}">
                                        <div th:if="${messageId} != null">
                                            <p th:text="${messageId}" class="alert alert-danger"></p>
                                        </div>
                                        <div class="form-group">
                                            <input type="text" class="form-control form-control-user"
                                                id="m_id" name="m_id" aria-describedby="emailHelp"
                                                placeholder="ID">
                                        </div>
                                        <div th:if="${messagePwd} != null">
                                            <p th:text="${messagePwd}" class="alert alert-danger"></p>
                                        </div>
                                        <div class="form-group">
                                            <input type="password" class="form-control form-control-user"
                                                id="m_password" name="m_password" placeholder="Password">
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-checkbox small">
                                                <input type="checkbox" class="custom-control-input" id="remember-me" name="remember-me">
                                                <label class="custom-control-label" for="remember-me">Remember-Me</label>
                                            </div>
                                        </div>
<!--                                        <a href="login" class="btn btn-primary btn-user btn-block">-->
<!--                                            Login-->
<!--                                        </a>-->
                                        <button type="submit" class="btn btn-primary btn-user btn-block">Login</button>
                                    </form>
                                    <hr>
                                    <div class="text-center">
                                        <a class="small" href="forgot-password.html">Forgot Password?</a>
                                    </div>
                                    <div class="text-center">
                                        <a class="small" href="/register">Create an Account!</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

        </div>

    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="../bootstrap/vendor/jquery/jquery.min.js"></script>
    <script src="../bootstrap/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../bootstrap/vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../bootstrap/js/sb-admin-2.min.js"></script>

</body>

</html>

 
 

실행

임시 테스트를 위해 MainController 게시글 작성 페이지에 session if 문을 넣어놓았다

    /**
     * 게시글 작성 페이지
     * @return
     * @throws Exception
     */
    @GetMapping("/board/create")
    public String boardCreate(HttpSession session) throws Exception{
        String user = (String) session.getAttribute("user");

        if(user == null){
            return "login";
        }else {
            return "BoardCreate";

        }
    }

 

localhost:9090 접속 시 session이 없어서 login 화면이 나올 것이고
로그인 전 localhost:9090/board/create 로 이동하였을때 session 을 확인하여 어디로 이동하는지,
로그인 후 localhost:9090/board/create 로 이동하면 어디로 이동하는지

localhost:9090 접속 -&gt; login 화면으로 전환

 
 

localhost:9090/board/create 접속 -&gt; login 화면으로 이동됨

 
 
 

login 테스트

 

정상적으로 login 이 됨

 

정상적으로 화면 이동됨

 
 

logout 클릭

 

session 삭제로 logout 확인

 

session 은 구현하기 간편하다는 장점이 있지만
Key와 value로 이루어진 session 을 서버에 저장하다보니 
여러개의 서버가 있다고 가정한다면 내가 login 한 서버에만
session이 존재한다는 단점이 있다
 
이를 해결하기 위한 방법이 있지만 여기서 다루지는 않겠다
 

 

댓글