spring boot
UserDetailService
파워킴
2020. 4. 17. 01:12
반응형
1. UserDeatilService 란.
login경로 등을 통해 전달된 로그인 id/pw 정보가 유효한지에 대해 Authentification Manager를 통해 검증하기 위한 서비스이다.
2. 구현.
- UserDetailsService 를 상속받은 구현체를 구현함.
- loadUserByUsername 를 Override 하여 User 정보를 셋팅함.
@Service
@Slf4j
public class ApiUserDetailService implements UserDetailsService {
@Autowired
PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("UserName, {}", username);
User.UserBuilder users = User.builder();
users.username("user1").password(passwordEncoder.encode("password1")).roles("USER", "ADMIN");
return users.build();
}
}
- AuthenticationManagerBuilder auth 객체에 DetailService 를 셋팅해줌. 이후 DetailService에서 로그인 정보에 대한 유효성을 체크함.
auth.userDetailsService(apiDetailService);
@Slf4j
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public ApiUserDetailService apiDetailService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(WebSecurity web) {
// web.ignoring().antMatchers("/img/**", "/js/**", "/hhadminvendor/**", "/favicon.ico", "/livecheck");
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(apiDetailService);
// .inMemoryAuthentication().withUser("user1").password( passwordEncoder().encode("password1") ).roles("USER", "ADMIN");
}
/* @formatter:off */
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().disable() // Http basic Auth 기반으로 로그인 인증창이 뜸. disable 시에 인증창 뜨지 않음.
.csrf().disable() // rest api이므로 csrf 보안이 필요없으므로 disable처리.
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증하므로 stateless 하도록 처리.
.and()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/hello2").authenticated() // 인증권한이 필요한 페이지.
.anyRequest().permitAll() // 나머지 모든 요청 허용 ( 생략 가능 )
;
}
/* @formatter:on */
}
3. 동작확인
반응형