진행되고 있는 트랜잭션에서 다른 트랜잭션이 호출될 때 어떻게 처리할지 정하는 것을 '트랜잭션의 전파 설정'이라고 부른다.
사용자를 인증(Authentication)하고, 사용자에 대한 권한을 체크(Authorization)하는 작업을 구현한 보안 라이브러리
Spring Starters를 통해 Spring Security 라이브러리를 추가한다.
WebSecurityConfig.java 파일을 생성한다.
// 설정이 스프링에 의해 읽혀져야해서 Ioc Container에 담겨져야 함
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 요청이 오면 인증, 권한이 필요한 요청인지 확인
http
.authorizeRequests()
.antMatchers("/admin/notice/list").hasAnyRole("ADMIN") // 인증을 필요로 하는 주소 + ADMIN(db에 등록한 데이터)만 접속하게 하겠다고 작성
.antMatchers("/admin/notice/detail").hasAnyRole("ADMIN")
.and() // 끝내기
.formLogin() // 인증이 안됐으면 로그인 페이지로 넘기기
.loginPage("/member/login") // 인증 정보를 가지고 있지 않다면 여기서 로그인을 하려고 해도 로그인이 안됨
.and()
.csrf() // csrf 설정은 보류
.disable();
}
// 1. inMemory 사용
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 관리자 페이지로 들어갈 수 있는 첫 유저가 필요 -> inmemory 사용해 사용자 고정해놓기
auth
.inMemoryAuthentication() // 사용자 인증 정보를 메모리에 넣고 바로 쓰는 것
.withUser("newlec")
.password("{noop}111") // 이건 암호화되있지 않은 패스워드라고 알려주는 것: {noop} -> 암호화가 안됐으면 인코더는 필요없음
.roles("ADMIN", "TEACHER")
.and()
.withUser("minju")
.password("{noop}111")
.roles("STUDENT");
// .and()
// .passwordEncoder(new BCryptPasswordEncoder());
}
}
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// DB 정보를 읽어 Data Source 객체를 만들어 IOC에 담게 됨
@Autowired
private DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
// 요청이 오면 인증, 권한이 필요한 요청인지 확인
http
.authorizeRequests()
.antMatchers("/admin/notice/list").hasAnyRole("ADMIN") // 인증을 필요로 하는 주소 + ADMIN(db에 등록한 데이터)만 들어가게 하겠다고 작성
.antMatchers("/admin/notice/detail").hasAnyRole("ADMIN")
.and() // 끝내기
.formLogin() // 인증이 안됐으면 로그인 페이지로 넘기기
.loginPage("/member/login") // 인증 정보를 가지고 있지 않다면 여기서 로그인을 하려고 해도 로그인이 안됨
.and()
.csrf() // csrf 설정은 보류
.disable();
}
// 2. DB 사용
// 인증을 하기 위한 사용될 데이터베이스 정보 주기
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
// 사용자 정보 가져오기
.usersByUsernameQuery("select uid id, pwd password, 1 enabled from Member where uid=?") // select에 들어가는 컬럼 순서가 스프링에서 정해져있어서 맞춰져야함(id, password, enabled)
// 해당 사용자의 역할 정보 가져오기
.authoritiesByUsernameQuery("select m.uid id, r.name roleId "
+ "from Member m "
+ "join MemberRole mr on m.id = mr.memberId "
+ "join Role r on r.id = mr.roleId "
+ "where m.uid = ?");
}
}