@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/assets/**", "/h2-console/**");
}
h2 데이터베이스의 console을 사용할 수 있도록 security 필터를 거치지 않도록 설정해주어야 한다.
spring:
sql:
init:
platform: h2
schema-locations: classpath:sql/schema.sql
data-locations: classpath:sql/data.sql
encoding: UTF-8
@Component
public class DataSourcePostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DataSource && !(bean instanceof Log4jdbcProxyDataSource)) {
return new Log4jdbcProxyDataSource((DataSource) bean);
} else {
return bean;
}
}
}
public class Log4jdbcProxyDataSource implements DataSource {
getConnection() throws SQLException {
Connection connection = this.realDataSource.getConnection();
// 데코레이터 패턴 이용
return new ConnectionSpy(connection, DriverSpy.getRdbmsSpecifics(connection));
}
}
retrieveUser()
: 사용자를 조회해오는 역할을 한다.UserDetailsService 인터페이스 구현체로 InMemoryUserDetailsManager 객체를 등록한다.
loadUserByUsername()를 이용하여 DB에서 사용자 인증 정보를 가져올 수 있다.
@Bean
public UserDetailsService userDetailsService(DataSource dataSource) {
JdbcDaoImpl jdbcDao = new JdbcDaoImpl();
jdbcDao.setDataSource(dataSource);
jdbcDao.setEnableAuthorities(false);
jdbcDao.setEnableGroups(true);
jdbcDao.setUsersByUsernameQuery(
"SELECT " +
"login_id, passwd, true " +
"FROM " +
"USERS " +
"WHERE " +
"login_id = ?"
);
jdbcDao.setGroupAuthoritiesByUsernameQuery(
"SELECT " +
"u.login_id, g.name, p.name " +
"FROM " +
"users u JOIN groups g ON u.group_id = g.id " +
"LEFT JOIN group_permission gp ON g.id = gp.group_id " +
"JOIN permissions p ON p.id = gp.permission_id " +
"WHERE " +
"u.login_id = ?"
);
return jdbcDao;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
// .userDetailsService() 직접 구현한 userDetailsService 참조를 넘겨줄 수 있다.
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(
"SELECT " +
"login_id, passwd, true " +
"FROM " +
"USERS " +
"WHERE " +
"login_id = ?"
)
.groupAuthoritiesByUsername(
"SELECT " +
"u.login_id, g.name, p.name " +
"FROM " +
"users u JOIN groups g ON u.group_id = g.id " +
"LEFT JOIN group_permission gp ON g.id = gp.group_id " +
"JOIN permissions p ON p.id = gp.permission_id " +
"WHERE " +
"u.login_id = ?"
)
.getUserDetailsService().setEnableAuthorities(false)
;
}