[Spring] Spring 시큐리티

김장환·2022년 9월 8일

Spring

목록 보기
17/17

스프링 시큐리티를 이용한 웹보안을 정리해보려한다.
예제로 SpirngSecurity 프로젝트를 만들고 이전처럼 진행하면서 정리해보려한다.


환경설정을 먼저 하자면 우선 lib에 라이브러리들 복사해서 넣는다
이건 이미 넣어있다고 가정하고 넘어가겠다.


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>SpringSecurity</display-name>
  
  <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/spring-security.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 환경설정파일명을 변경하거나 다른경로로 지정 
			init-param태그로 지정
	-->
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:/spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- 보안필터를 적용 
			DelegatingFilterProxy (인증을 처리해주는 클래스)
	-->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 한글처리 -->
	<filter>
	  <filter-name>encoding</filter-name>
	  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	  <init-param>
	   <param-name>encoding</param-name>
	   <param-value>UTF-8</param-value>
	  </init-param>
	</filter>
	
	<filter-mapping>
	  <filter-name>encoding</filter-name>
	  <url-pattern>/*</url-pattern>
	</filter-mapping>
  
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

spring-mvc.xml 가져온 후 작성

  • < mvc:annotation-driven /> 사용
    => 어노테이션기반의 컨트롤러 호출이나 필요로한 빈객체를 설정(편리하게)
  • < mvc:default-servlet-handler/>
    => 메핑에 따라서 처리(/hello (hello.jsp))
    .html, .css 같은 요청을 처리할수 없기에 디폴트 서블릿에서 처리
    요청URL에 메핑되는 컨트롤러가 존재하지 않을때 404응답대신에
    디폴트서블릿이 해당 요청URL 처리하도록 설정
  • < mvc:view-controller path=""/>
    =>요청하면 이동시켜준다
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<!-- 어노테이션기반의 컨트롤러 호출이나 필요로한 빈객체를 설정(편리하게) -->
	<mvc:annotation-driven />
	
	<!-- 메핑에 따라서 처리(/hello (hello.jsp)) 
		*.html, *.css 같은 요청ㄹ을 처리할수 없기에 디폴트 서블릿에서 처리
		요청URL에 메핑되는 컨트롤러가 존재하지 않을때 404응답대신에 디폴트서블릿이 해당 요청URL 처리하도록 설정
	-->
	<mvc:default-servlet-handler/>
	
	<!-- path(요청경로) view-name="이동할 페이지명" 
		/index로 요청하면 /WEB-INF/view/index.jsp로 이동
	-->
	<mvc:view-controller path="/index" view-name="index" />
	<mvc:view-controller path="/home/main" view-name="homeMain" />
	<mvc:view-controller path="/manager/main" view-name="managerMain" />
	<mvc:view-controller path="/admin/main" view-name="adminMain" />
	<mvc:view-controller path="/member/main" view-name="memberMain" />
	
	
	
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

Spring-security.xml 가져온후 작성

  • 1.SpEL(스프링표현식)을 사용하도록 설정(패턴,접근설정)
  • 2.접근목록(name(암호),password(암호) authorities(사용자가 갖는 권학목록을 지정)

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:sec="http://www.springframework.org/schema/security"
	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
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd">

	<!-- 1.SpEL(스프링표현식)을 사용하도록 설정 (패턴,접근설정)
			use-expressions="true"
			intercept-url->접근권한을 설정할때 사용
			pattern=>접근경로 설정
			access=>해당경로에 누가 접근가능한지 설정
			hasAuthority(ROLE_ADMIN)->ROLE_ADMIN접근권한을 가진자 설정
			hasAuthority()와 hasRole()은 같은 의미
			isAuthenticated()=>인증된 사용자만 접근이 가능하도록 설정
			permitAll=>누구나 접근이 가능하다는것을 뜻한다.
			<sec:form-login/>인증된 사용자만 허용되는 자원(경로)에 접근할때 로그인폼을 보여준다. 로그인폼에서 아이디/암호를 전송,인증처리
			<sec:logout/> 로그아웃 처리를 위한 기능을 추가한다.
	 -->
   	<sec:http use-expressions="true">
   		<sec:intercept-url pattern="/admin/**" access="hasAuthority('ROLE_ADMIN')" />
   		<sec:intercept-url pattern="/manager/**" access="hasRole('ROLE_MANAGER')" />
   		<sec:intercept-url pattern="/member/**" access="isAuthenticated()" />
   		<sec:intercept-url pattern="/**" access="permitAll" />
   		<sec:form-login/>
   		<sec:logout/>
   	</sec:http>
   	
   	<!-- 2.접근목록(name(암호),password(암호) 
   			authorities(사용자가 갖는 권학목록을 지정)-->
   	<sec:authentication-manager>
   		<sec:authentication-provider>
   			<sec:user-service>
   				<sec:user name="kjh" password="1234" authorities="ROLE_USER"/>
   				<sec:user name="manager" password="qwer" authorities="ROLE_MANAGER"/>
   				<sec:user name="admin" password="asdf" authorities="ROLE_ADMIN,ROLE_USER"/>
   			</sec:user-service>
   		</sec:authentication-provider>
   	</sec:authentication-manager>
</beans>

adminMain.jsp 생성
=> view폴더만들고 그안에 생성

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
	<title>어드민 메인</title>
</head>
<body>
어드민(연결 계정: <sec:authentication property="name"/>) 메인 화면입니다.
<br/>
<a href="<c:url value='/index'/>">[/index로 가기]</a>
</body>
</html>


index.jsp 생성
-sec:authorize 커스텀태그는 현재 사용자가 특정권한이 있으면 몸체내용을 보여주는 기능을 제공한다.

  • sec:authentication=>현재 접속한 사용자의 인증정보를 보여준다.
    property="name" -> name속성값을 출력
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
	<title>인덱스 페이지</title>
</head>
<body>
<!-- 
	sec:authorize 커스텀태그는 현재 사용자가 특정권한이 있으면 몸체내용을 보여주는 기능을 제공한다.
	sec:authentication=>현재 접속한 사용자의 인증정보를 보여준다.
		  property="name" -> name속성값을 출력
 -->
<sec:authorize access="isAuthenticated()">
	<sec:authentication property="name" />님 환영합니다.
</sec:authorize>

<ul>
	<li><a href="<c:url value='/home/main' />">/home/main</a></li>
	<li><a href="<c:url value='/member/main' />">/member/main</a></li>
	<li><a href="<c:url value='/manager/main' />">/manager/main</a></li>
	<li><a href="<c:url value='/admin/main' />">/admin/main</a></li>
	<sec:authorize access="isAuthenticated()">
		<li><a href="<c:url value='/j_spring_security_logout' />">j_spring_security_logout'</a></li>
	</sec:authorize>
</ul>

</body>
</html>


homeMain.jsp 생성

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
	<title>홈 메인</title>
</head>
<body>

<sec:authorize access="isAuthenticated()">
	<sec:authentication property="name" />님 환영합니다.
</sec:authorize>

홈 메인 화면입니다.
<a href="<c:url value='/index'/>">[/index로 가기]</a>

</body>
</html>


memberMain.jsp 생성

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
	<title>멤버 메인</title>
</head>
<body>


멤버 이름:<sec:authentication property="name" />님 환영합니다.


<a href="<c:url value='/index'/>">[/index로 가기]</a>

</body>
</html>


managerMain.jsp 생성


<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
	<title>매니저 메인</title>
</head>
<body>


매니저 이름:<sec:authentication property="name" />님 환영합니다.


<a href="<c:url value='/index'/>">[/index로 가기]</a>

</body>
</html>

실행시킬 index.jsp 생성
=> view에 만든 index.jsp가아니라 새로 만든 실행시킬 index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0;url=<c:url value='/index' />">
</head>
<body>

</body>
</html>

실행 후 잘 되면 성공이다


2022-09-08

0개의 댓글