1. 의존성 추가
: build.gradle 파일에 Spring Security 의존성을 추가한다.
implementation 'org.springframework.boot:spring-boot-starter-security'
2. Security Config 클래스 작성
: Spring Security의 설정을 정의하는 클래스를 작성한다.
WebSecurityConfigurerAdapter를 상속받아 구현한다.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/signup").permitAll() // 회원가입 페이지는 모든 사용자에게 허용
.antMatchers("/admin").hasRole("ADMIN") // /admin 페이지는 ADMIN 권한이 있는 사용자만 허용
.anyRequest().authenticated() // 그 외의 모든 요청은 인증된 사용자에게만 허용
.and()
.formLogin()
.loginPage("/login").permitAll() // 로그인 페이지는 모든 사용자에게 허용
.and()
.logout().permitAll(); // 로그아웃은 모든 사용자에게 허용
}
}
위 코드에서는 /signup 페이지는 모든 사용자에게 허용하고, /admin 페이지는 ADMIN 권한이 있는 사용자만 접근할 수 있다. 그 외의 모든 요청은 인증된 사용자에게만 허용하고, 로그인 페이지와 로그아웃은 모든 사용자에게 허용한다.
3. 사용자 정보와 권한 설정
: 사용자 정보와 권한은 데이터베이스에 저장하거나 메모리에 임시로 설정할 수 있다.
UserDetailsService를 구현하여 설정한다.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
// 패스워드를 인코딩할 PasswordEncoder를 설정한다.
return BCryptPasswordEncoder.getInstance();
}
}
위와 같이 기본적인 설정을 통해 Spring Security를 사용하여 Spring Boot에서 권한을 설정할 수 있다. 실제로는 사용자 정보를 데이터베이스에 저장하고, 패스워드를 암호화하는 등의 추가적인 보안 설정을 해야 하며, 보안 헤더 설정, CSRF 보호, 세션 관리 등의 추가 작업도 필요할 수 있다.
'BackEnd > spring' 카테고리의 다른 글
| CSRF / JWT / CSRF 토큰과 JWT의 차이점 (0) | 2023.08.09 |
|---|---|
| Spring Security란? (0) | 2023.08.09 |
| [Spring Boot] 의존성 주입 / 객체 생성 방법 - 멤버변수와 생성자, @Configuration과 @Bean (0) | 2023.06.14 |
| [Spring Boot] Spring Service (0) | 2023.06.14 |
| [Spring Boot] HTTP Method와 데이터베이스 CRUD (0) | 2023.06.09 |