본문 바로가기
스프링

Spring Security - 스프링 시큐리티 활용 방법

by CodeMango 2023. 8. 28.

Spring Security(스프링 시큐리티)

스프링 시큐리티는 스프링 기반의 애플리케이션의 보안(인증과 권한,인가 등)을 담당하는 스프링 하위 프레임워크이다. 주로 서블릿 필터와 이들로 구성된 필터체인으로의 위임모델을 사용한다. 그리고 보안과 관련해서 체계적으로 많은 옵션을 제공해주기 때문에 개발자 입장에서는 일일이 보안관련 로직을 작성하지 않아도 된다.

 

보안 용어

 

  • 접근 주체(Principal) : 보호된 리소스에 접근하는 대상
  • 인증(Authentication) : 보호된 리소스에 접근한 대상에 대해 이 유저가 누구인지, 애플리케이션의 작업을 수행해도 되는 주체인지 확인하는 과정(ex. Form 기반 Login)
  • 인가(Authorize) : 해당 리소스에 대해 접근 가능한 권한을 가지고 있는지 확인하는 과정(After Authentication, 인증 이후)
  • 권한 : 어떠한 리소스에 대한 접근 제한, 모든 리소스는 접근 제어 권한이 걸려있다. 즉, 인가 과정에서 해당 리소스에 대한 제한된 최소한의 권한을 가졌는지 확인한다.

Spring Security(스프링 시큐리티)란?

스프링 시큐리티는 스프링 기반의 애플리케이션의 보안(인증과 권한,인가 등)을 담당하는 스프링 하위 프레임워크이다. 주로 서블릿 필터와 이들로 구성된 필터체인으로의 위임모델을 사용한다. 그리고 보안과 관련해서 체계적으로 많은 옵션을 제공해주기 때문에 개발자 입장에서는 일일이 보안관련 로직을 작성하지 않아도 된다.

 

 

위의 그림은 Form 기반 로그인에 대한 플로우를 보여주는 그림이다.

  1. 사용자가 Form을 통해 로그인 정보를 입력하고 인증 요청을 보낸다.
  2. AuthenticationFilter(사용할 구현체 UsernamePasswordAuthenticationFilter)가 HttpServletRequest에서 사용자가 보낸 아이디와 패스워드를 인터셉트한다. 프론트 단에서 유효성검사를 할 수도 있지만, 무엇보다 안전! 안전을 위해서 다시 한번 사용자가 보낸 아이디와 패스워드의 유효성 검사를 해줄 수 있다.(아이디 혹은 패스워드가 null인 경우 등) HttpServletRequest에서 꺼내온 사용자 아이디와 패스워드를 진짜 인증을 담당할 AuthenticationManager 인터페이스(구현체 - ProviderManager)에게 인증용 객체(UsernamePasswordAuthenticationToken)로 만들어줘서 위임한다.
  3. AuthenticationFilter에게 인증용 객체(UsernamePasswordAuthenticationToken)을 전달받는다.
  4. 실제 인증을 할 AuthenticationProvider에게 Authentication객체(UsernamePasswordAuthenticationToken)을 다시 전달한다.
  5. DB에서 사용자 인증 정보를 가져올 UserDetailsService 객체에게 사용자 아이디를 넘겨주고 DB에서 인증에 사용할 사용자 정보(사용자 아이디, 암호화된 패스워드, 권한 등)를 UserDetails(인증용 객체와 도메인 객체를 분리하지 않기 위해서 실제 사용되는 도메인 객체에 UserDetails를 상속하기도 한다.)라는 객체로 전달 받는다.
  6. AuthenticationProvider는 UserDetails 객체를 전달 받은 이후 실제 사용자의 입력정보와 UserDetails 객체를 가지고 인증을 시도한다.
  7. 8. 9. 10. 인증이 완료되면 사용자 정보를 가진 Authentication 객체를 SecurityContextHolder에 담은 이후 AuthenticationSuccessHandle를 실행한다.(실패시 AuthenticationFailureHandler를 실행한다.)

 

Spring Web Security의 설정

1) pom.xml에 dependency 추가

https://docs.spring.io/spring-security/site/docs/5.6.0-M2/reference/html5/

 

Spring Security Reference

In Spring Security 3.0, the codebase was sub-divided into separate jars which more clearly separate different functionality areas and third-party dependencies. If you use Maven to build your project, these are the modules you should add to your pom.xml. Ev

docs.spring.io


스프링 공식 문서에는 spring-security-web만 존재하지만 다양한 처리를 하기 위해 아래와 같이 web,config,core도 pom.xml에 추가하도록 한다. (3개는 모두 동일한 버전일 것)

<!-- 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-config -->
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-config</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>

JSP에서 스프링 시큐리티 관련된 태그 라이브러리를 활용하기 위해 아래의 spring-security-taglibs도 추가한다.

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

(pom.xml의 내용을 수정하면 반드시 maven update 해주기🙋‍♀️)

2) security-context.xml생성

스프링 시큐리티는 단독으로 설정할 수 있기 때문에 기존의 root-context.xml이나 servlet-context.xml과는 별도로 security-context.xml을 작성하는 것이 좋다.
xml이나, Spring Bean Configuration File로 security-context.xml파일을 생성한다.

 

security-context.xml의 위치는 아래의 경로와 같다.

 

작성한 security-context.xml의 namespace에서 security항목을 체크한다.

 

3) web.xml 설정

스프링 시큐리티를 스프링 MVC에서 사용하기 위해 필터를 이용해서 스프링 동작에 관여하도록 설정한다.

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


기존에 아래처럼 있었던 것을

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>

security-context.xml의 경로를 추가하여 설정파일의 위치를 알려주는 아래의 코드로 변경해준다.

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

 

4) 다시 security-context.xml로 돌아와서

스프링 시큐리티가 동작하기 위해서는 Authenrication Manager라는 존재와 스프링 시큐리티의 시작 지점이 필요하기 때문에 위와 같이 최소한의 설정을 지정한 후에 실행한다.

(xml을 이용해서 스프링 시큐리티를 설정할 때 5.0 네임스페이스에서 문제가 발생한다고 함.
<beans> 태그 내용 중에서 -5.0.xsd라고 쓰여진 부분을 제거하고 아래와 같이 수정해주었으니 참고하기)

<?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.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<security:http>
		<security:form-login />
	</security:http>
	<security:authentication-manager>
	</security:authentication-manager>
</beans>


서버를 실행하였을 때 에러가 발생하지 않는다면 스프링 시큐리티의 최소한의 설정은 마무리 된 것이다!

'스프링' 카테고리의 다른 글

[스프링, 스프링부트] GET vs POST parameter  (0) 2023.04.02
[스프링] 자료실 , bean 개념  (0) 2023.02.28

댓글