읽은 책 정리/코드로 배우는 스프링 웹 프로젝트

[Spring] 30 Spring web Security 설정과 기본원리 소개

포포015 2021. 2. 5. 15:38

스프링 시큐리티의 기본동작은 서블릿의 여러종류의 필터와 인터셉터를 이용해 처리 된다

 

필터 - 서블릿에서 말하는 단순한 필터

인터셉터 - 스프링에서 필터와 유사한 역할

 

결정 적인 차이는 필터는 > 스프링과 무관하게 서블릿자원

                       인터셉터는 > 스프링의 빈으로 관리되면서 스프링의 컨텍스트내에 속한다

 

이론은 나중에 따로 공부하도록 하고 실습을 해보자..

 

1) ex06 프로젝트를 생성하고, 스프링 버전을 조정하자 

스프링 시큐리티는 스프링의 여러 하위 프로젝트중 하나이므로 필요한 버전을 추가( 다양한 처리를 위해 여러개 추가)

pom.xml 에 라이브러리를 추가(3개의 라이브러리는 동일한 버전으로 맞추기)

JSP 에서 스프링 시큐리티 관련된 태그 라이브러리를 활용할수 있도록 spring -sucurity -taglib 를 추가한다.

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
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>5.0.6.RELEASE</version>
</dependency>
 
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>5.0.6.RELEASE</version>
</dependency>
 
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>5.0.6.RELEASE</version>
</dependency>    
 
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>5.0.6.RELEASE</version>
</dependency>
cs

 

2) 스프링 시큐리티는 단독으로 설정할수 있기때문에 별도로 파일을 작성한다.

security-context.xml 따로 작성.(WEB-INF/spring 아래에 생성하자..(Spring Bean Configuration File 메뉴를 통해 생성)

- 네임스페이스에서 security 항목체크 (5.0으로 생성되는데 버전만 지워주자)

 

3) web.xml 설정 스프링 시큐리티가 스프링 MVC에 사용되기 위해서는 필터를 이용해서 스프링 동작에 관여하도록 함

 아래의 코드를 추가한다 

1
2
3
4
5
6
7
8
9
10
    <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>
 
cs

(위와 같이 추가하면 에러가 발생하는데 springSecurityFilterChain 이라는 빈이 제대로 설정되지 않는다고 나오는데,

 스프링 시큐리티 설정 파일을 찾을수 없기 때문이다) > 

 

web.xml 상단부분을 수정

1
2
3
4
5
6
7
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
                     /WEB-INF/spring/root-context.xml
                     /WEB-INF/spring/security-context.xml
        </param-value>
    </context-param>
cs

 

security-context.xml 에설정 (최소한의 설정을 추가해준다)

스프링 시큐리티가 동작하기위해서는 Authentication-manage라는 존재와

스프링 시큐리티의 시작점이 필요하다 !!!!

1
2
3
4
5
6
7
8
9
10
11
    <!-- 시큐리티의 시작점 -->
    <security:http>
        
        <security:form-login/>
        
    </security:http>
 
    <!-- 스프링 시큐리티 동작하기위해 필요한 존재 -->
    <security:authentication-manager>
    
    </security:authentication-manager>
cs

 

나머지는 패키지 내에 클래스를 작성하고 uri 에 맞는 메서드와 뷰단을 작성해서 테스트를 해보면 정상작동 한다..

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Log4j
@Controller
@RequestMapping("/sample")
public class SampleController {
 
    @GetMapping("/all")
    public void doAll() {
        
        log.info("all---------");
    }
    
    @GetMapping("/member")
    public void doMember() {
        
        
        log.info("member-------");
    }
    
    @GetMapping("/admin")
    public void doAdmin() {
        
        log.info("admin------");
    }
cs

 

 

 

******************************************************************************************************************************

인증(Authentication)과 권한 부여(Authorization - 인가)

인증은 쉽게 말해서 '자신을 증명하는것' (자기 스스로 무언가 자신을 증명한 자료를 제시하는것)

권한부여는 남에 의해서 자격이 부여된다는점의 차이가 있다.

(인증 - 본인이 무엇인가를 증명하는 행위)

(권한부여 - 인증의 과정이 거치고 , 담당자에 의해 어떤 게시물에 대한 조회를 하거나 ,수정할수 있는 권한이 부여됨)

 

스프링 시큐리티내부도 이와 같은 비슷한 구조를 가지고있다.

1. 가장 중요한 역할을 하는 존재가 인증을 담당하는 AuthenticationManager(인증매니저)라는 존재이다.

2. ProviderManager는 인증에 대한 처리를 AuthenticationProvider 라는 타입의 객체를 이용해 처리를 위임함

3. AuthenticationProvider(인증 제공자)는 실제 인증 작업을 진행한다.

이때 인증된 정보에는 권한에 대한 정보를 같이 전달하는데 이처리는 UserDetailsService 라는 존재와 관련 있다.

UserDetailsService 인터페이스의 구현체는 실제로 사용자의 정보와 사용자가 가진 권한의 정보를 처리해서 반환한다.

 

실제 개발자가 커스텀마이징 하는 방식은 크게 

 - 1) AuthenticationManager를 직접 구현하는 방식과 , 2) UserDetailsService를구현하는방식으로나누어진다

 

대부분의 경우 UserDetailsService 를 구현하는 형태를 사용 하는것으로 충분하지만

새로운 프로토콜이나, 인증 구현 방식을 직접 구현하는경우 AuthenticationManager 인터페이스를 직접 구현해야한다.