build.gradle에 의존성 추가
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}
ORM 기술로 JPA, 보안을 위한 스프링 시큐리티, View 템플릿 타임리프와 롬복, MariaDB 등을 추가했습니다.
Config 패키지 생성 후 Sring Security 관리 클래스 생성
package com.sh.springsec.config;
import com.sh.springsec.service.UserService;
import lombok.RequiredArgsConstructor;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@RequiredArgsConstructor
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/css/**", "/js/**", "/img/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/signup", "/user").permitAll()
.antMatchers("/").hasRole("USER")
.antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login") // 로그인 페이지 링크
.defaultSuccessUrl("/") // 로그인 성공 후 리다이렉트 주소
.and()
.logout()
.logoutSuccessUrl("/login") // 로그아웃 성공시 리다이렉트 주소
.invalidateHttpSession(true); // 세션 날리기
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
}
}
Spring Security를 사용하기 위해 WebSecurityConfigurerAdater를 상속받은 Security Config 클래스를 만들었습니다. Spring Security 사용을 위해서는 @EnableWebSecurity 어노테이션을 달아줘야 합니다. 위에서 오버라이딩한 메소드는 configure 메소드는 각각 WebSecurity, HttpSecurity와 AuthenticationManagerBuilder를 매개변수로 받습니다.
메소드 역할
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/css/**", "/js/**", "/img/**");
}
스프링 시큐리티 인증 없이도 접근 가능하게 할 경로를 설정합니다.
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/signup", "/user").permitAll()
.antMatchers("/").hasRole("USER")
.antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.and()
.logout()
.logoutSuccessUrl("/login")
.invalidateHttpSession(true);
}
권한에 따라 접근할 수 있는 경로를 지정합니다.
메소드 |
역할 |
.authorizeRequests() |
시큐리티 처리에 HttpServletRequest를 사용 |
.antMatchers(String) |
특정 경로를 지정 |
.hasRole(String) |
지정된 경로에 특정 권한을 가진 사용자만 접근 가능 |
.permitAll() |
지정된 경로에 모든 사용자가 접근 가능 |
.anyRequest() |
위에서 지정되지 않은 경로 |
.authenticated() |
권한을 갖지 않은 사용자를 로그인 페이지로 리다이렉트 |
.formLogin() |
커스텀 로그인 페이지에 관한 설정 |
.loginPage(String) |
로그인 페이지 지정 |
.defaultSuccessUrl(String) |
로그인 성공 시 리다이렉트 할 페이지 지정 |
.logout() |
로그아웃 설정 |
.logoutSuccessUrl(String) |
로그아웃 성공 시 리다이렉트 할 페이지 지정 |
.invalidateHttpSession(boolean) |
로그아웃 후 사용자 권한과 세션의 제거 여부 설정 |