2016년 8월 30일 화요일

Spring Security 인증방법 4가지.

JavaConfig 방식 기준으로 이야기를 하면 다음과 같다.
.xml 설정은 찾아보면 많이들 있더라.

1. in-memory

2. jdbc database

3. UserDetailsService

4. AuthenticationProvider

샘플 코드는 아래를 참조.
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private AuthServiceImpl authService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
AdminUser user = (AdminUser) authService.loadUserByUsername(username);
if (user == null || !user.getUsername().equalsIgnoreCase(username)) {
throw new BadCredentialsException("Username not found.");
}
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
if (!passwordEncoder.matches(password, user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
@Configuration
@EnableWebSecurity
public class WebMvcConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("userName")
.password("password")
.roles("ADMIN")
;
}
}
@Configuration
@EnableWebSecurity
public class WebMvcConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery(
"select username, password, enabled from admin_users where username=?")
.authoritiesByUsernameQuery(
"select username, role from user_roles where username=?")
;
}
}
@Configuration
@EnableWebSecurity
public class WebMvcConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(adminService)
;
}
}