우당탕탕

Spring Security 권한 설정 방법 쉽게 배우기! 본문

카테고리 없음

Spring Security 권한 설정 방법 쉽게 배우기!

모찌모찝 2026. 5. 9. 20:03

Spring Security란?

안녕하세요! 오늘은 백엔드 개발자분들이라면 반드시 알아야 할 Spring Security에 대해서 알아보려고 합니다. 웹 애플리케이션을 안전하게 보호하기 위한 프레임워크인데요, 권한 설정이 핵심입니다. 하지만 처음 접할 때는 어렵게 느껴질 수 있죠. 그럼, 어떻게 권한 설정을 쉽게 할 수 있을까요? 함께 알아보겠습니다!

Spring Security 기본 설정

먼저, Spring Security를 사용하기 위해 기본적인 설정을 해줘야 합니다. 의존성을 추가하고, 웹 보안을 설정하는 방법을 알아볼게요.

    • 프로젝트의 pom.xml에 아래 의존성을 추가합니다:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
    • 이제 WebSecurityConfigurerAdapter를 상속받아 보안 설정 클래스를 작성합니다:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin();
    }
}

위의 설정으로 기본적인 로그인 폼이 제공되며, 모든 요청은 인증이 필요하게 됩니다. 이제 권한 설정을 추가해볼까요?

Spring Security 권한 설정 방법 관련 이미지
Spring Security 권한 설정 방법 관련 정보

역할 기반 권한 설정

Spring Security의 강력한 기능 중 하나는 역할 기반의 권한 설정입니다. 예를 들어, 특정 사용자에게 관리자 권한을 부여하고 싶다면 아래와 같이 설정할 수 있습니다.

    1. 사용자 역할을 정의합니다:
public enum Role {
    USER,
    ADMIN
}
    1. 사용자 인증 정보를 설정합니다:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .withUser("user").password(passwordEncoder().encode("password")).roles(Role.USER.name())
        .and()
        .withUser("admin").password(passwordEncoder().encode("adminpass")).roles(Role.ADMIN.name());
}

이제 사용자에 따라 다른 권한을 부여할 수 있습니다. 특정 URL에 대해 권한을 설정하려면 다음과 같이 추가하세요:

http
    .authorizeRequests()
    .antMatchers("/admin/**").hasRole(Role.ADMIN.name())
    .antMatchers("/user/**").hasRole(Role.USER.name())
    .anyRequest().authenticated();

이렇게 하면, 관리자 역할을 가진 사용자만 /admin 경로에 접근할 수 있습니다.

Spring Security 권한 설정 방법 관련 이미지
Spring Security 권한 설정 방법 관련 정보

메모리 외부 저장소 사용하기

프로젝트가 커질수록 사용자 인증을 메모리에 저장하는 것은 비효율적입니다. 그래서 데이터베이스를 활용하는 방법도 알아볼게요. 우선 JDBC를 이용한 설정을 추가합니다.

    • 의존성을 추가합니다:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
    • 데이터베이스 설정을 해줍니다:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root

그런 다음, UserDetailsService를 구현하여 사용자 정보를 DB에서 가져올 수 있습니다:

@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getAuthorities());
    }
}

이제 데이터베이스를 통해 사용자 인증을 할 수 있습니다.

Spring Security 권한 설정 방법 관련 이미지
Spring Security 권한 설정 방법 관련 정보

자주 묻는 질문 (FAQ)

1. Spring Security에서 기본 로그인 페이지는 어떻게 사용하나요?

Spring Security를 추가하면 기본 로그인 페이지가 자동으로 생성됩니다. 따로 설정하지 않아도 됩니다!

2. 사용자 비밀번호는 어떻게 안전하게 저장하나요?

비밀번호는 PasswordEncoder를 사용하여 암호화한 후 데이터베이스에 저장해야 합니다.

3. 권한 설정을 다양한 방식으로 할 수 있나요?

네, URL 패턴 기반, 메서드 기반 등 여러 방식으로 세분화된 권한 설정이 가능합니다.

마무리

오늘은 Spring Security 권한 설정 방법에 대해서 알아보았습니다. 웹 애플리케이션의 보안을 강화하고 사용자 권한을 적절히 설정하는 것이 중요하죠. 이 글이 도움이 되셨다면 댓글로 알려주세요! 꿀팁이나 궁금한 점도 언제든지 환영합니다!

Comments