[java] 롬복을 사용하여 자바 인증과 보안을 어떻게 처리하고 사용할 수 있나요?

롬복(Lombok)은 자바 언어를 위한 개발 도구로, 보일러플레이트(Boilerplate) 코드를 줄여주고, 코드 가독성을 향상시키는 기능을 제공합니다. 롬복은 인증과 보안과 같은 고급 기능을 처리하는 데도 유용하게 사용될 수 있습니다.

자바에서 인증과 보안 처리를 위해 대부분의 개발자들은 스프링 시큐리티(Spring Security) 프레임워크를 사용합니다. 롬복과 스프링 시큐리티를 함께 사용하여 코드를 간결하게 작성할 수 있습니다.

롬복을 사용한 스프링 시큐리티 설정

  1. 먼저, 프로젝트의 의존성에 롬복과 스프링 시큐리티를 추가해야 합니다. pom.xml 파일에 다음의 의존성을 추가해주세요:

    <dependencies>
      <!-- 롬복 의존성 -->
      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <scope>provided</scope>
      </dependency>
    
      <!-- 스프링 시큐리티 의존성 -->
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
    </dependencies>
    
  2. 롬복 어노테이션을 사용하여 스프링 시큐리티 관련 클래스를 작성합니다. 예를 들어, 사용자를 나타내는 User 클래스를 다음과 같이 작성할 수 있습니다:

    import lombok.*;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetails;
    
    import java.util.Collection;
    
    @Getter
    @Setter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public class User implements UserDetails {
        private String username;
        private String password;
        private Collection<? extends GrantedAuthority> authorities;
    }
    

    위의 코드에서 @Getter, @Setter, @Builder, @NoArgsConstructor, @AllArgsConstructor는 롬복 어노테이션으로, 겟터, 셋터, 빌더 및 생성자 코드를 자동으로 생성해줍니다.

  3. UserDetailsService 인터페이스를 상속받아 사용자 인증 정보를 가져오는 커스텀 서비스 클래스를 작성합니다. 롬복 어노테이션을 사용하여 코드를 간소화합니다:

    import lombok.RequiredArgsConstructor;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;
    
    @Service
    @RequiredArgsConstructor
    public class CustomUserDetailsService implements UserDetailsService {
        private final UserRepository userRepository;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found"));
            return user;
        }
    }
    

    위의 코드에서 @Service는 스프링의 서비스 빈으로 등록되도록 해주는 롬복 어노테이션입니다.

  4. 마지막으로, 스프링 시큐리티 설정 클래스를 작성합니다. 롬복을 사용하여 코드를 더 간결하게 만듭니다:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.UserDetailsService;
    
    @Configuration
    @EnableWebSecurity
    @RequiredArgsConstructor
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        private final UserDetailsService userDetailsService;
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .logout().permitAll();
        }
    }
    

    위의 코드에서 @EnableWebSecurity는 스프링 시큐리티를 활성화하도록 해주는 롬복 어노테이션입니다.

이제 롬복을 사용하여 스프링 시큐리티를 구성하는 방법을 알았습니다. 롬복을 사용하면 코드의 가독성과 유지 보수성을 향상시킬 수 있으므로, 이를 통해 자바 인증과 보안을 손쉽게 처리할 수 있습니다.

참고 자료