Backend/Spring

[Spring] Spring Boot Web Mvc에 Spring Security 시작하기

mirae.kwak 2022. 8. 30. 21:06
728x90

Spring Security

Spring Boot 웹 어플리케이션에 적용 가능하며 적은 노력으로 각 상황에 보안을 적용할 수 있다.

https://miraekwak.tistory.com/130

 

[Spring] 웹 어플리케이션 보안 위협 요소

웹 어플리케이션의 주요 보안 위협 요소 인증(Authentication) 절차 마비 인증(Authentication)은 인가(Authorization)와 함께 보안 관련 핵심 개념 중 하나이다. 사용자의 신원을 확인하는 과정은 아이디/패

miraekwak.tistory.com

사용자 인증 및 인가 처리는 기본이며 필요에 따라 커스터마이징이 가능하다. 다양한 확장 기능과 자연스러운 통합이 가능하다.

  • Spring Session 세션 클러스터 기능 추상화 제공

https://spring.io/projects/spring-session

 

Spring Session

This project uses a Maven BOM (Bill of Materials) and a release train to coordinate versions, e.g. 2121.1.1, 2020.0.3, etc. Using the BOM with Maven With Maven, you need to import the BOM first: org.springframework.session spring-session-bom 2021.1.1 pom i

spring.io

  • Spring Security Oauth ( Oauth 1a, Oauth2 인증 프로토콜 제공 )

https://spring.io/projects/spring-security-oauth

 

Spring Security OAuth

The Spring Security OAuth project has reached end of life and is no longer actively maintained by VMware, Inc.

spring.io

 

Spring Security 시작하기

의존성 추가

  • spring-boot-starter-security : spring security 모듈
  • spring-security-test : security 테스트 모듈
  • thymeleaf-extras-springsecurity5 : thymeleaf spring security 확장 모듈 
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.thymeleaf.extras</groupId>
  <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

 

Java Configuration

@Configuration
@EnableWebSecurity
public class WebSecurityConfigure extends WebSecurityConfigurerAdapter {

  @Override
  public void configure(WebSecurity web) {
    web.ignoring().antMatchers("/assets/**");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
        .antMatchers("/me").hasAnyRole("USER", "ADMIN") // 인증영역
        .anyRequest().permitAll()
        .and()
      .formLogin() // Spring security가 자동으로 로그인 페이지 생성
        .defaultSuccessUrl("/")
        .permitAll()
    ;
  }

}
  • @EnableWebSecurity 어노테이션, WebSecurityConfigureAdapter 클래스 상속
    • WebSecurityConfigureAdapter 추상클래스를 상속하는 구현체에 @EnableWebSecurity 어노테이션을 추가
    • 기본적인 Spring Security 설정이 자동으로 추가되며, 개별 설정을 override 할 수 있음
  • WebSecurity 클래스는 필터 체인 관련 전역 설정을 처리할 수 있는 API 제공
    • ignoring()
      • Spring Security 필터 체인을 적용하고 싶지 않은 리소스에 대해 설정
      • 일반적으로 정적 리소스(*.html, *.css, *.js 등)을 예외 대상으로 설정함
      • 불필요한 서버 자원 낭비를 방지함
  • HttpSecurity 클래스는 세부적인 웹 보안 기능을 설정을 처리할 수 있는 API제공

 

Http Security 주요 메소드

메소드명 설명
authorizeRequests() 공개 리소스 또는 보호받는 리소스에 대한 세부 설정
formLogin()  로그인 폼 기능 세부설정
logout() 로그아웃 기능 세부설정
rememberMe() 자동 로그인 기능 세부 설정

 

기본 로그인 계정 설정 추가

기본 로그인 계정을 추가하지 않으면 매번 랜덤으로 비밀번호가 생성된다.

  • UserDetailServiceAutoConfigure 클래스 구현을 보면 InMemoryUserDetailsManager (InMemory 기반 사용자 관리 UserDetailService) Bean을 등록함
    • InMemoryUserDetailsManager Bean 생성 시 SecurityProperties 클래스를 통해 spring.security 관련 설정을 처리함
    • 즉 여기서 기본 계정, 계정명, user 등이 설정됨
    • SecurityProperties에서는 기본적으로 user를 하나 들고 있는데 이 user의 생성자에서 password가 randomUUID로 자동으로 만들어짐
    • 콘솔에서 만들어진 password가 출력됨
  • applicaition.yml 파일에 기본 로그인 계정 정보를 입력함
    • 물론 실제 프로젝트에서는 이런식으로 사용자 계정을 관리하지 않음
spring:
  application:
    name: spring security 01
  thymeleaf:
    cache: true
  security:
    user:
      name: user
      password: user123
			roles: USER
  messages:
    basename: i18n/messages
    encoding: UTF-8
    cache-duration: PT1H
server:
  port: 8080

 

Thymeleaf 확장

thymeleaf-extras-springsecurity5 라이브러리를 추가하면 Thymeleaf View에서 Spring Security 관련 기능을 쉽게 사용 가능하다.

<html xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:text="${#authentication.name}">
  The value of the "name" property of the authentication object should appear here.
</div>

<div th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}">
  This will only be displayed if authenticated user has role ROLE_ADMIN.
</div>

<div sec:authentication="name">
  The value of the "name" property of the authentication object should appear here.
</div>

<div sec:authorize="hasRole('ROLE_ADMIN')">
  This will only be displayed if authenticated user has role ROLE_ADMIN.
</div>

 

728x90