본문 바로가기
Spring/Spring 기초

e7e샘의 시큐리티 설정

by 미눅스[멘토] 2023. 8. 29.
728x90

 

 

 

 

Spring Legacy Project생성

 

 

 

Project name설정 후에

Spring MVC Project선택후 넥스트

 

 

패키지 네임 설정후 피니쉬

 

 

 

생성된 프로젝트 우클릭 후 Properties클릭

 

 

 

Project Facets 선택해서 java파일 내 버전으로 설정

 

 

 

 

 

Dynamic Web Module 버전 설정

톰켓 9는 4.0대를 지원

톰켓 8은 3.0대를 지원 구글치면 나옴

 

 

 

다됬으면 어플라이 클릭

 

 

이렇게 설정하고

콘솔에 보면 이렇게 두 개 오류난거 확인

 

src/test/resources 파일 안에 log4j.xml파일 삭제 이유는 필요없음

 

 

삭제하고 나면 오류가 하나밖에 안남음

남은 오류는 log4j.dtd가  없다는 뜻인데

 

이거는 구글에 검색해서 다운하면 됨

 

 

 

 

다운로드 받았으면

 

 

 

이 오류나있는 경로에 복사해서 갔다 붙인다.

 

rec/main/resources안에 복사

 

 

 

 

그리고 프로젝트 클린 한번 하셈

 

그럼 오류 전부 사라짐

 

 

 

그리고 web.xml에가서

 

 

여기부분 내 버전으로 바꿈

 

 

이렇게 치면 나옴 거기서 나는 4.0버전이기 때문에 나는 4.0으로 검색함

 

 

코드 복사해서

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">

 

 

붙여넣음

 

web.xml = 톰캣 설정 파일

 

 

 

log.xml로 가서

 

 

내거만금은 debug로 변경해준다

이거 하나 복사해서

 

 

시큐리티로 설정

 

 

시큐리티에서 암호화하는것중에 BVrypt라는게 있음

pom.xml 아래코드 붙여 넣기

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.minu</groupId>
	<artifactId>sec</artifactId>
	<name>SecBasic</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.3.29</org.springframework-version>
		<org.aspectj-version>1.9.19</org.aspectj-version>
		<org.slf4j-version>2.0.7</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- @Validation , API 2.0(JSR-380), 구현체 하이버네이트 6.X-->		
		<dependency>
		    <groupId>javax.validation</groupId>
		    <artifactId>validation-api</artifactId>
		    <version>2.0.1.Final</version>
		</dependency>
		<dependency>
		    <groupId>org.hibernate.validator</groupId>
		    <artifactId>hibernate-validator</artifactId>
		    <version>6.1.5.Final</version>
		</dependency>
		
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.3</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- HikariCP -->
		<dependency>
			<groupId>com.zaxxer</groupId>
			<artifactId>HikariCP</artifactId>
			<version>4.0.3</version>
		</dependency>

		<!-- ojdbc8 -->
		<dependency>
			<groupId>com.oracle.database.jdbc</groupId>
			<artifactId>ojdbc8</artifactId>
			<version>23.2.0.0</version>
		</dependency>

		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.13</version>
		</dependency>

		<!-- mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.1.1</version>
		</dependency>

		<!-- spring-jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<!-- jackson-databind -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.15.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.28</version>
			<scope>provided</scope>
		</dependency>

		<!-- 스프링 시큐리티 -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>5.8.6</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>5.8.6</version>
		</dependency>

		<!-- Test -->
		<!-- junit-jupiter-engine -->
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<version>5.10.0</version>
			<scope>test</scope>
		</dependency>

		<!-- spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</version>
			<scope>test</scope>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.10</version>
				<configuration>
					<additionalProjectnatures>
						<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
					</additionalProjectnatures>
					<additionalBuildcommands>
						<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
					</additionalBuildcommands>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.11.0</version>
				<configuration>
					<source>${java-version}</source>
					<target>${java-version}</target>
					<compilerArgument>-Xlint:all</compilerArgument>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>3.1.0</version>
				<configuration>
					<mainClass>org.test.int1.Main</mainClass>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

 

스프링 시큐리티가 들어가있는것을 볼 수 있음

 

 

그럼 롬복 로딩되어야 하니 X눌러서 껏다킴

 

 

 

홈 콘트롤러에가서 @Slf4j 달아주고

스프링에서 자주사용하는 패스워드 인코더 객체 생성해봄

 

서버 재실행해서

확인해보면

 

angel과 angma 는 서로 다른걸 엔코딩해주는것을 볼 수 있음

 

matches라는게 있음 이거 확인해보면

true를 반환한 것을 볼 수 있음

 

 

피니쉬

 

 

 

 

그다음 하단에 Namespaces클릭해서

 

 

security 체크

 

 

 

다시 security-context.xml에 가보면 이렇게 뭔가 추가되어있다.

 

버전이 있는데 버전(숫자)만 지워줌

 

 

////////////////////////////<잠시 상식>//////////////////////////

get으로 오면 login화면

post로 오면 처리

 

인증 = 석일이가 석일이라고 말했을때 석일이인지 확인하는 것

ㄴ본인이 본인이 맞는지 아닌지(identity)

 

인가 = 수지가 민우집 들어가서 컴퓨터를 부술 수 있는 권한이 있는지

ㄴ권한

 

 

 

 

 

그래서 이렇게 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"
   xmlns:security="http://www.springframework.org/schema/security"
   xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-5.8.xsd
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
      
      <bean id="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
      <!--웹 보안  -->
      <security:http auto-config="true">
      </security:http>
      
      <security:authentication-manager>
         <security:authentication-provider>
            <security:password-encoder ref="bCryptPasswordEncoder"/>
            <security:user-service>
               <security:user name="jinsu" 
                     password="$2a$10$qLWALnVsCYJhVavUKl8HKuwDQM4WXLEHqurqJQJslEEwoS7c8nXiS" 
                     authorities="ROLE_SUJI"/>
            </security:user-service>
         </security:authentication-provider>
      </security:authentication-manager>
      
</beans>

 

 

이제 읽어갈 파일 만들자

root-context.xml에서

import 시켜줌

 

https://e-7-e.tistory.com/53

이거 참고

 

 

이거 복사해서

이게 하는역할은 공항에 경찰같은거라 생각하면됨

공항에서 검문검색 해주는애

	<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>

 

 

web.xml에 맨 밑에 붙여넣기

여기까지 해놓고

login까지 쳐보면

 

 

다시 security-context.xml로가서 url도 설정해줌

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:security="http://www.springframework.org/schema/security"
   xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-5.8.xsd
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
      
      <bean id="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
      <!--웹 보안  -->
      <security:http auto-config="true">
      	<security:intercept-url pattern="/*" access="hasRole('ROLE_SUJI')" />
      </security:http>
      
      
      <security:authentication-manager>
         <security:authentication-provider>
            <security:password-encoder ref="bCryptPasswordEncoder"/>
            <security:user-service>
               <security:user name="jinsu" 
                     password="$2a$10$qLWALnVsCYJhVavUKl8HKuwDQM4WXLEHqurqJQJslEEwoS7c8nXiS" 
                     authorities="ROLE_SUJI"/>
            </security:user-service>
         </security:authentication-provider>
      </security:authentication-manager>
</beans>

 

 

 

이렇게하고

컨트롤러 생성

package com.minu.sec.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/angma")
public class SecController {

	@GetMapping("/minu")
	public String minu() {
		return "minu";
	}
	
	@GetMapping("/hyunhak")
	public String hyunhak() {
		return "hyunhak";
	}
}



security-context.xml에서 URL다시 설정

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:security="http://www.springframework.org/schema/security"
   xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-5.8.xsd
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
      
      <bean id="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
      <!--웹 보안  -->
      <security:http auto-config="true">
      	<security:intercept-url pattern="/angma/*" access="hasRole('ROLE_SUJI')" />
      	<security:intercept-url pattern="/*" access="permitAll"/>
      </security:http>
      
      
      <security:authentication-manager>
         <security:authentication-provider>
            <security:password-encoder ref="bCryptPasswordEncoder"/>
            <security:user-service>
               <security:user name="jinsu" 
                     password="$2a$10$qLWALnVsCYJhVavUKl8HKuwDQM4WXLEHqurqJQJslEEwoS7c8nXiS" 
                     authorities="ROLE_SUJI"/>
            </security:user-service>
         </security:authentication-provider>
      </security:authentication-manager>
</beans>

 

 

확인해보셈

 

 

 

 

그럼 다시.....

Controller에 가서...

수정하고 실행해보묜.,...

package com.minu.sec.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/angma")
public class SecController {

	@GetMapping("/minu")
	public String minu(Authentication auth) {
		log.debug("auth : "+ auth);
		log.debug("auth : "+ auth.getPrincipal());
		log.debug("auth : "+ auth.getAuthorities());
		
		
		//시큐리티 뽀인트!
		SecurityContext secCont = SecurityContextHolder.getContext();
		
		log.debug("check : " + secCont);
		
		return "minu";
	}
	
	@GetMapping("/hyunhak")
	public String hyunhak() {
		return "hyunhak";
	}
}

 

 

 

 

콘솔에 이러한 값들이 있는것을 볼 수 있음..

 

그럼 다시 이렇게 해서 확인...

package com.minu.sec.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/angma")
public class SecController {

	@GetMapping("/minu")
	public String minu(Authentication auth) {
		log.debug("auth : "+ auth);
		log.debug("auth : "+ ((User)auth.getPrincipal()).getUsername());
		log.debug("auth : "+ ((User)auth.getPrincipal()).getPassword());
		log.debug("auth : "+ auth.getAuthorities());
		
		
		//시큐리티 뽀인트!
		SecurityContext secCont = SecurityContextHolder.getContext();
		
		log.debug("check : " + secCont);
		
		return "minu";
	}
	
	@GetMapping("/hyunhak")
	public String hyunhak() {
		return "hyunhak";
	}
}

 

 

이제 로그아웃 만들기

security-context에  이걸 true로 하면 로그인과 로그아웃을 만들어줌

그래서 이제 로그아웃 만들어 볼거임

 

minu.jsp에가서 폼을 만들고 action을 /ogout으로 지정한다.

<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>

ㄴ이거 필수!! 그래야 csrf토큰을 사용할 수 있음

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>미누천사</h1>
<form action="/sec/logout" method="post">
	<sec:csrfInput/>
	<button>로그아웃 이지용!!</button>
</form>
</body>
</html>

 

그리고 확인