ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스프링부트 스프링시큐리티 연동하기(4) 커스텀login.jsp/join.jsp/home.jsp
    Spring Security 2019. 6. 29. 21:46
    반응형

    1.시큐리티 커스텀 로그인 login.jsp 작성

    (login.jsp)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>로그인</title>
    <script
      integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
      crossorigin="anonymous"></script>
      <!-- 합쳐지고 최소화된 최신 CSS -->
    <!-- 부가적인 테마 -->
    </head>
    <body>
        <div class="container">
            <div class="row" style="padding-top:20%">
                   <div class="col-md-4 "></div>
                   <div class="col-md-4" style="flex-align:center">
                       <div class="card">
                           <h5 class="card-header">로그인</h5>
                          <div class="card-body">
                               <form action="/login/login-processing" method='POST' >
    <%--                             <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> --%>
                                   <div class="form-group">
                                       <label for="InputId"> 아이디</label>
                                       <input type="text" class="form-control" id="id" name="id" placeholder="ID">
                                    </div>
                                   <div class="form-group">
                                       <label for="InputPassword1">패스워드</label>
                                       <input type="password" class="form-control" id="password" name="password" placeholder="Password">
                                   </div>
                                   <div class="checkbox">
                                       <label>
                                           <input type="checkbox" name="remember-me"> 아이디 기억하기
                                       </label>
                                   </div>
                                   <button name="submit" type="submit" class="btn btn-block btn-primary text-light">로그인</button>
                               </form>
                           </div>
                      </div>
                   </div>
            </div>      
        </div>
    </body>
    <script>
        $(document).ready(function(){
            <c:if test="${not empty msg}">
                alert('${msg}');
            </c:if>
        });
    </script>
    </html>
     
     

    ccs는 부트스트랩을 사용하였고 form action 주소,id,password input name은 config에 설정한 로그인 프로세스를 수행하는 url을 적었다.

    2.회원가입 join.jsp 작성

    (join.jsp)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>회원가입</title>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
      <!-- 합쳐지고 최소화된 최신 CSS -->
    <!-- 부가적인 테마 -->
        <style>
            /* .help-block 을 일단 보이지 않게 설정 */
            #myForm .help-block{
                display: none;
            }
            /* glyphicon 을 일단 보이지 않게 설정 */
            #myForm .glyphicon{
                display: none;
            }
        </style>
    </head>
    <body>
    <div class="container">
        <h3>회원가입 폼 입니다.</h3>
        <form action="/join/insert" method="post" id="myForm">
            <div class="form-group has-feedback">
                <label class="control-label" for="id">아이디</label>
                <input class="form-control" type="text" name="id" id="id"/>
                <span id="overlapErr" class="help-block">사용할 수 없는 아이디 입니다.</span>
                <span class="glyphicon glyphicon-ok form-control-feedback"></span>
            </div>
            <div class="form-group has-feedback">
                <label class="control-label" for="memberName">이름</label>
                <input class="form-control" type="text" name="memberName" id="memberName"/>
            </div>
            <div class="form-group has-feedback">
                <label class="control-label" for="pwd">비밀번호</label>
                <input class="form-control" type="password" name="password" id="password"/>
                <span id="pwdRegErr" class="help-block">8글자 이상 입력하세요.</span>
                <span class="glyphicon glyphicon-ok form-control-feedback"></span>
            </div>
            <div class="form-group has-feedback">
                <label class="control-label" for="rePwd">비밀번호 재확인</label>
                <input class="form-control" type="password" name="rePwd" id="rePwd"/>
                <span id="rePwdErr" class="help-block">비밀번호와 일치하지 않습니다. 다시 입력해 주세요.</span>
                <span class="glyphicon glyphicon-ok form-control-feedback"></span>
            </div>
            <div class="form-group has-feedback">
                <label class="control-label" for="email">이메일</label>
                <input class="form-control" type="text" name="email" id="email"/>
                <span id="emailErr" class="help-block">올바른 이메일 형식이 아닙니다. 다시 입력해 주세요.</span>
                <span class="glyphicon glyphicon-ok form-control-feedback"></span>
            </div>
            <div class="form-group has-feedback">
                <label class="control-label" for="userRole">권한</label>
                <select class="form-control" id="userRole" name="userRole">
                      <option value="ROLE_USER">일반회원</option>
                      <option value="ROLE_ADMIN">관리자</option>
                </select>
            </div>
            <button class="btn btn-success" type="submit">가입</button>
        </form>
    </div>
    <script>
        //아이디 입력란에 keyup 이벤트가 일어 났을때 실행할 함수 등록 
        $("#id").keyup(function(){
            //입력한 문자열을 읽어온다.
            var id=$(this).val();
            //ajax 요청을 해서 서버에 전송한다.
            $.ajax({
                method:"post",
                url:"/join/idCheck",
                data:{inputId:id},
                success:function(data){
                    console.log(data);
                    if(data){//사용 가능한 아이디 라면 
                        $("#overlapErr").hide();
                        // 성공한 상태로 바꾸는 함수 호출
                        successState("#id");
                        
                    }else{//사용 가능한 아이디가 아니라면 
                        $("#overlapErr").show();
                        errorState("#id");
                    }
                }
            });
        });
        $("#password").keyup(function(){
            var pwd=$(this).val();
            // 비밀번호 검증할 정규 표현식
            var reg=/^.{8,}$/;
            if(reg.test(pwd)){//정규표현식을 통과 한다면
                        $("#pwdRegErr").hide();
                        successState("#password");
            }else{//정규표현식을 통과하지 못하면
                        $("#pwdRegErr").show();
                        errorState("#password");
            }
        });
        $("#rePwd").keyup(function(){
            var rePwd=$(this).val();
            var pwd=$("#password").val();
            // 비밀번호 같은지 확인
            if(rePwd==pwd){//비밀번호 같다면
                $("#rePwdErr").hide();
                successState("#rePwd");
            }else{//비밀번호 다르다면
                $("#rePwdErr").show();
                errorState("#rePwd");
            }
        });
        $("#email").keyup(function(){
            var email=$(this).val();
            // 이메일 검증할 정규 표현식
            var reg=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if(reg.test(email)){//정규표현식을 통과 한다면
                        $("#emailErr").hide();
                        successState("#email");
            }else{//정규표현식을 통과하지 못하면
                        $("#emailErr").show();
                        errorState("#email");
            }
        });
        // 성공 상태로 바꾸는 함수
        function successState(sel){
            $(sel)
            .parent()
            .removeClass("has-error")
            .addClass("has-success")
            .find(".glyphicon")
            .removeClass("glyphicon-remove")
            .addClass("glyphicon-ok")
            .show();
     
            $("#myForm button[type=submit]")
                        .removeAttr("disabled");
        };
        // 에러 상태로 바꾸는 함수
        function errorState(sel){
            $(sel)
            .parent()
            .removeClass("has-success")
            .addClass("has-error")
            .find(".glyphicon")
            .removeClass("glyphicon-ok")
            .addClass("glyphicon-remove")
            .show();
     
            $("#myForm button[type=submit]")
                        .attr("disabled","disabled");
        };
    </script>    
    </body>
    </html>

    아이디 중복체크를 하고 회원가입을 하는 페이지를 작성하였다.

    가입시 권한 셀렉트 박스를 만들고 value에 권한명을 넣었다. 권한을 부여하는 방법은 개발자가 마음대로 하면된다.

    3.로그인 후 이동되는  home.jsp 작성

    (home.jsp)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>로그인 성공</title>
    <script
      integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
      crossorigin="anonymous"></script>
      <!-- 합쳐지고 최소화된 최신 CSS -->
    <!-- 부가적인 테마 -->
    </head>
    <body>
        <div class="container">
            <h1>로그인 성공</h1>
            
            - 권한을 체크하는 태그 입니다.
            <br/>
            * 로그인 되지 않았다면 [TRUE] 입니다.
            <br/>
            <sec:authorize access="isAnonymous()">[TRUE]</sec:authorize>
            <br/>
            <br/>
            * 로그인 했다면 참입니다.
            <br/>
            &nbsp;&nbsp;<sec:authorize access="isAuthenticated()">[TRUE]</sec:authorize>
            <br/>
            
            * 인자로 주어진 ROLE_ADMIN을 가지고 있다면 [TRUE]입니다.
            <br/>
            <br/>
            &nbsp;&nbsp;<sec:authorize access="hasRole('ROLE_ADMIN')">[TRUE]</sec:authorize>
            <br/>
            * 인자로 주어진 ROLE_USER을 가지고 있다면 [TRUE]입니다.
            <br/>
            &nbsp;&nbsp;<sec:authorize access="hasRole('ROLE_USER')">[TRUE]</sec:authorize>
            <br/>
            <br/>
            * 인자로 주어진 ROLE_ADMIN을 가지고 있지 않다면 [TRUE]입니다.
            <br/>
            &nbsp;&nbsp;<sec:authorize access="!hasRole('ROLE_ADMIN')">[TRUE]</sec:authorize>
            <br/>
            <br/>
            * 인자로 주어진 ROLE_USER을 가지고 있지 않다면 [TRUE]입니다.
            <br/>
            &nbsp;&nbsp;<sec:authorize access="!hasRole('ROLE_USER')">[TRUE]</sec:authorize>
            <br/>
            <br/>
            * 인자로 주어진 롤들중 하나라도 가지고 있다면 [TRUE]입니다.
            <br/>
            &nbsp;&nbsp;<sec:authorize access="hasAnyRole('ROLE_ADMIN','ROLE_USER')">[TRUE]</sec:authorize>
            <br/>
            <br/>
            * 이 사용자는 "Rememember Me Cookies"로 자동 로그인이라면 [TRUE]입니다.
               <br/>
               &nbsp;&nbsp;<sec:authorize access="isRememberMe()">[TRUE]</sec:authorize>
             <br/>
            <br/>
             * 이 사용자는 사용자 아이디/비밀번호로 로그인 하고 있으면 [TRUE]입니다.
             <br/>
            &nbsp;&nbsp;<sec:authorize access="isFullyAuthenticated()">[TRUE]</sec:authorize>
            <br/>
            <br/>
            <a href="/login/logout">[로그아웃]</a>
        </div>
    </body>
    </html>

    성공적으로 로그인이 되고 이동되는 페이지이다.

    스프링 시큐리티에서 제공하는 태그라이브러리로 현재 로그인 정보를 출력 한다.

    이렇게 jsp까지 작성을 마치고 시큐리티 기본 연동은 끝났다.

    마지막으로 샘플 소스는 아래의 깃허브 주소에서 확인 할 수 있다.

    https://github.com/DevMoonKi/SpringBootSecuritySample

     

    반응형

    댓글

Designed by Tistory.