JSP security 인증, 권한

별의개발자커비·2023년 4월 30일
0

JSP

목록 보기
12/31
post-thumbnail

1. tomcat-user.xml에 role 수정

  • server - tomcat-user.xml - source 에서 role, user 풀고 수정하기

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><tomcat-users version="1.0" xmlns="http://tomcat.apache.org/xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd">
<!--
  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary.

  Built-in Tomcat manager roles:
    - manager-gui    - allows access to the HTML GUI and the status pages
    - manager-script - allows access to the HTTP API and the status pages
    - manager-jmx    - allows access to the JMX proxy and the status pages
    - manager-status - allows access to the status pages only

  The users below are wrapped in a comment and are therefore ignored. If you
  wish to configure one or more of these users for use with the manager web
  application, do not forget to remove the <!.. ..> that surrounds them. You
  will also need to set the passwords to something appropriate.
-->
<!--
  <user username="admin" password="<must-be-changed>" roles="manager-gui"/>
  <user username="robot" password="<must-be-changed>" roles="manager-script"/>
-->
<!--
  The sample user and role entries below are intended for use with the
  examples web application. They are wrapped in a comment and thus are ignored
  when reading this file. If you wish to configure these users for use with the
  examples web application, do not forget to remove the <!.. ..> that surrounds
  them. You will also need to set the passwords to something appropriate.
-->

  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat1234" roles="tomcat"/>
  <user username="both" password="both1234" roles="tomcat,role1"/>
  <user username="role1" password="role1234" roles="role1"/>

  <role rolename="manager"/>
  <user username="admin" password="admin1234" roles="manager"/>

</tomcat-users>

2. WEB-INF - web.xml 파일에 권한 코드 추가

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
  </welcome-file-list>

	<security-role>
		<role-name>manager</role-name>
	</security-role>
	<security-constraint>
		<!-- 웹 자원에 대한 설정 -->
		<web-resource-collection>
			<!-- 자원 이름 -->
			<web-resource-name>BookStore</web-resource-name>
			<!-- 접근 제한 url -->
			<url-pattern>/cart/security01.jsp</url-pattern>
			<url-pattern>/cart/security02.jsp</url-pattern>
            <!-- 2-1. security02-->
			<url-pattern>/shoppingmall/addProduct.jsp</url-pattern>
			<!-- 전송 방식 -->
			<http-method>GET</http-method> 
		</web-resource-collection>
		<!-- 인증된 사용자 -->
		<auth-constraint>
			<description>관리자</description>
			<role-name>manager</role-name>
		</auth-constraint>
		
<!--   		데이터 보호
		<user-data-constraint>
			NONE/INTEGRAL/CONFIDENTIAL: 기본값(데이처보호x) / 무결성(전송 중에 변경되지 않도록) / 기밀성
			<transport-guarantee>CONFIDENTIAL</transport-guarantee>
		</user-data-constraint>  -->
		
	</security-constraint>
	<login-config>
		<!-- <auth-method>BASIC</auth-method> -->
		<auth-method>FORM</auth-method>
		<form-login-config>
        	<!-- 4. shoppingmall/ login.jsp, loginfailed.jsp -->
			<form-login-page>/shoppingmall/login.jsp</form-login-page>
			<form-error-page>/shoppingmall/login_failed.jsp</form-error-page>
		</form-login-config>
	</login-config>
 	
 	<!-- 예외처리 페이지 -->
 	<!-- 우선순위 1)jsp 페이지에 설정한 애 > 2)exception-type > 3)error-code -->
 	<!-- 최우선순위: 코드 내의 것 -->
 	
 	<!-- 3순위. 코드에 의해 발생하는 애 error-code -->
 	<error-page>
	 	<error-code>404</error-code>
	 	<location>/shoppingmall/error_404.jsp</location>
 	</error-page>
 	 <error-page>
	 	<error-code>500</error-code>
	 	<location>/shoppingmall/error_500.jsp</location>
 	</error-page>
 		
 	<!-- 2순위. (유형별) 타입에 의해 발생하는 애 exception-type -->
 	<error-page>
 		<exception-type>java.lang.Exception</exception-type>
 		<location>/shoppingmall/exception_error.jsp</location>
 	</error-page>
 	
<context-param>
	<param-name>log4jConfigLocation</param-name>
	<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<listener>
	<listener-class></listener-class>
</listener>
 	
</web-app>

01. http-method

: GET

02. auth-method

1. 'BASIC'

<auth-method>BASIC</auth-method>

2. 'FORM'

<form-login-config>
		<form-login-page>/shoppingmall/login.jsp</form-login-page>
		<form-error-page>/shoppingmall/login_failed.jsp</form-error-page>
	</form-login-config>

03. login.jsp

04. security02

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>security02</title>
</head>
<body>
	<p> 사용자명 : <%=request.getRemoteUser() %>
	<p> 인증방법 : <%= request.getAuthType() %>
	<p> 인증한 사용자명이 역활명 "manager"에 속하는 사용자인가요?: <%= request.isUserInRole("manager") %>
	<p> 인증한 사용자명이 역활명 "role1"에 속하는 사용자인가요?: <%= request.isUserInRole("role1") %>
</body>
</html>
  • request.getRemoteUser() : 사용자명 manager
  • request.getAuthType() : 인증방법 GET
  • request.isUserInRole("manager") : true
  • request.isUserInRole("role1") : false

3. cart/login.jsp, loginfailed.jsp

01. login.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>
</head>
<body>
	<form action="j_security_check" name="loginForm" method="post">
		<p>아이디 <input type="text" name="j_username">
		<p>패스워드 <input type="password" name="j_password">
		<p><input type="submit" value="전송">
	</form>
</body>
</html>

02. loginfailed.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>
</head>
<body>
(cart)로그인 실패
</body>
</html>

03. form action="j_security_check"

https://keichee.tistory.com/333

  • 이거 쓰려면
    name="j_username"
    name="j_password"
    가 되어있고, 이걸 web.xml의 username과 password랑 비교해주는 거겠지?

4. shoppingmall/ login.jsp, loginfailed.jsp

01. login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" 
rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<meta charset="UTF-8">
<title>login</title>
</head>

<body>
<form action="j_security_check" name="loginForm" method="post">
	<jsp:include page="./menu.jsp"></jsp:include>
	<div class="container">
		<h1 class="display-3">로 그 인</h1>
	</div>
	<div class="container">
	  <div class="col-md-5">
	    <label for="exampleInputEmail1" class="form-label">ID</label>
	    <input type="text" name="j_username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
	    <div id="emailHelp" class="form-text">input the id</div>
	  </div>
	  <div class="col-md-5">
	    <label for="exampleInputPassword1" class="form-label">Password</label>
	    <input name="j_password" type="password" class="form-control" id="exampleInputPassword1">
	  </div>
	  <div class="col-md-5 form-check">
	    <input type="checkbox" class="form-check-input" id="exampleCheck1">
	    <label class="form-check-label" for="exampleCheck1">Check me out</label>
	  </div>
	  <button type="submit" class="btn btn-primary">Submit</button>
	</div>
</form>

</body>
</html>

02. loginfailed.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>
</head>
<body>
<%
	response.sendRedirect("login.jsp?error=1");
%>
</body>
</html>
	response.sendRedirect("login.jsp?error=1");
  • 로그인 인증(login.jsp)에 실패 시 강제 error=1 페이지로 이동

5. logout

01. addProduct.jsp 에 로그아웃 버튼 추가

<div class="text-right">
		<a href="logout.jsp" class="btn btn-sm btn-success pull-right">logout</a>
	</div>

02. logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>logout</title>
</head>
<body>
<%
	session.invalidate();		// 세션 죽여주는거
	response.sendRedirect("addProduct.jsp");		// 여기로 가게되면 로그인이 안되어있으니까 사실을 로그인페이지로 가게 됨
%>

</body>
</html>

03. session.invalidate();

  • 세션 죽여주는거

6. 에러, 예외 처리 errorpage

01. error 코드 우선순위

0순위: 코드 내의 것
1순위: jsp 페이지 상단에 설정한 애

근데 저 코드를 모든 페이지에? no! web.xml에 추가

2순위. (유형별) 타입에 의해 발생하는 애 exception-type
3순위. 코드에 의해 발생하는 애 error-code

02. errorPage.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%-- <%@ page errorPage="errorPage_error.jsp" %> --%>
<!-- 1순위 )jsp 페이지에 설정한 애 -->


 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>9. errorPage</title>
</head>
<body>
<%
request.getParameter("name").toCharArray();

// 0순위) 예외가 발생하면 특정 페이지로 이동 : 
	/* try{
	request.getParameter("name").toCharArray();
	} catch (Exception e ){
		RequestDispatcher dis = request.getRequestDispatcher("/shoppingmall/products.jsp");
		dis.forward(request, response);
	} */
%>
</body>
</html>

03. errorPage_error.jsp

// 에러처리되면 가는 곳
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>10. errorPage_error.jsp</title>
</head>
<body>
	<h1>에러가 발생했습니다.</h1>
</body>
</html>

04. web.xml

<!-- <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
  </welcome-file-list>

	<security-role>
		<role-name>manager</role-name>
	</security-role>
	<security-constraint>
		웹 자원에 대한 설정
		<web-resource-collection>
			자원 이름
			<web-resource-name>BookStore</web-resource-name>
			접근 제한 url
			<url-pattern>/cart/security01.jsp</url-pattern>
			<url-pattern>/cart/security02.jsp</url-pattern>
			<url-pattern>/shoppingmall/addProduct.jsp</url-pattern>
			전송 방식
			<http-method>GET</http-method> 
		</web-resource-collection>
		인증된 사용자
		<auth-constraint>
			<description>관리자</description>
			<role-name>manager</role-name>
		</auth-constraint>
		
  		데이터 보호
		<user-data-constraint>
			NONE/INTEGRAL/CONFIDENTIAL: 기본값(데이처보호x) / 무결성(전송 중에 변경되지 않도록) / 기밀성
			<transport-guarantee>CONFIDENTIAL</transport-guarantee>
		</user-data-constraint> 
		
	</security-constraint>
	<login-config>
		<auth-method>BASIC</auth-method>
		<auth-method>FORM</auth-method>
		<form-login-config>
			<form-login-page>/shoppingmall/login.jsp</form-login-page>
			<form-error-page>/shoppingmall/login_failed.jsp</form-error-page>
		</form-login-config>
	</login-config> -->
 	
<!-- 예외처리 페이지 -->	
 	<!-- 3순위. 코드에 의해 발생하는 애 error-code -->
 	<error-page>
	 	<error-code>404</error-code>
	 	<location>/shoppingmall/error_404.jsp</location>
 	</error-page>
 	 <error-page>
	 	<error-code>500</error-code>
	 	<location>/shoppingmall/error_500.jsp</location>
 	</error-page>
 		
 	<!-- 2순위. (유형별) 타입에 의해 발생하는 애 exception-type -->
 	<error-page>
 		<exception-type>java.lang.Exception</exception-type>
 		<location>/shoppingmall/exception_error.jsp</location>
 	</error-page>
 	
<!-- <context-param>
	<param-name>log4jConfigLocation</param-name>
	<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<listener>
	<listener-class></listener-class>
</listener>
 	
</web-app> -->

05. 에러 처리 페이지들

1) error_500.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link
	href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
	rel="stylesheet"
	integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
	crossorigin="anonymous">
<title>11. 500 에러</title>
</head>
<body>
	<jsp:include page="./menu.jsp"></jsp:include>
	<div class="container">
		<h1 class="display-3">500 에러</h1>
	</div>
	<h1>500 에러 발생</h1>
</body>
</html>

2) error_404.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link
	href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
	rel="stylesheet"
	integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
	crossorigin="anonymous">
<title>11. 404 에러 </title>
</head>
<body>
	<jsp:include page="./menu.jsp"></jsp:include>
	<div class="container">
		<h1 class="display-3">404에러</h1>
	</div>
	<h1>페이지를 찾을 수 없습니다.</h1>
	<h3>요청경로를 확인하세요.</h3>
</body>
</html>

3) exception_error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link
	href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
	rel="stylesheet"
	integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
	crossorigin="anonymous">
<title>12. 에러 exception_error</title>
</head>
<body>
	<jsp:include page="./menu.jsp"></jsp:include>
	<div class="container">
		<h1 class="display-3">exception 발생</h1>
	</div>
</body>
</html>

- menu에서 경로 수정

루트도 /bookstore에서 /로 server module에서 바꿔줘야함

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<nav class="navbar navbar-expand-lg bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="./welcome.jsp">Home</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      <div class="navbar-nav">
        <a id="productlist" class="nav-link active" aria-current="page" href="/shoppingmall/products.jsp">상품목록</a>
        <a id='productregister' class="nav-link" href="/shoppingmall/addProduct.jsp">상품등록</a>
        <a class="nav-link" href="#">other3</a>
        <a class="nav-link disabled">other4</a>
      </div>
    </div>
  </div>
</nav>

0. 로그 설정하기(다음시간)

다운로드 - lib 에 추가 - buildpath 에도 추가


profile
비전공자 독학러. 일단 쌔린다. 개발 공부👊

0개의 댓글