[스프링시큐리티] 사용자 정보 조회 / 인증 상세

Welcome to Seoyun Dev Log·2024년 12월 19일
0

보안

목록 보기
18/18

UserDetailsService

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/css/**", "/images/**", "/js/**", "/favicon.*", "/*/icon-*").permitAll() .requestMatchers("/").permitAll()
.anyRequest().authenticated())
.formLogin(form -> form.loginPage("/login").permitAll())
.userDetailsService(userDetailsService) // 커스텀 UserDetailService 설정; 

return http.build();
}

UserDetailsService 구현

@Service("userDetailsService")
@RequiredArgsConstructor
public class FormUserDetailsService implements UserDetailsService {

private final UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String username (사용자가 입력한 username)) throws UsernameNotFoundException {
  Account account = userRepository.findByUsername(username); 
  if (account == null) {
    if (userRepository.countByUsername(username) == 0) {
    throw new UsernameNotFoundException("No user found with username: " + username);
  	}
  }
  List<GrantedAuthority> authorities = List.of(new SimpleGrantedAuthority(account.getRoles())); // 권한 설정 ModelMapper mapper = new ModelMapper();
  AccountDto accountDto = mapper.map(account, AccountDto.class);
  }
	return new AccountContext(accountDto, authorities); 
    // AccountContext 는 UserDetails 를 구현한 클래스로서 AccountDto 를 Wrapping 함
}

AuthenticationProvider

AuthenticationProvider안에 UserDetails가 포함되어있는 것으로
AuthenticationProvider를 구현하여 적용하면 UserDetails를 설정하지 않아도 된다

@Override
public boolean support(Class<?> authentication){
	return authentication.isAssignablefrom(UsernamePasswordAuthenticationToken.class);
}

커스텀 인증상세 구현하기

: 사용자가 클라이언트에서 서버로 인증요청을 할 때 아이디와 비빌번호를 입력해서 보내주는데
이때 인증객체 Authentication에서 인증 작업을 하고, Details 객체에는 사용자의 IP 주소와 세션 ID와 같은 정보를 가지고 있다. 이 Details에 저장되어있는 객체가 WebAuthenticationDetails 객체이다

WebAuthenticationDetails

  • HTTP 요청과 관련된 인증 세부 정보를 포함하는 클래스로서 기본적으로 사용자의 IP 주소와 세션 ID와 같은 정보를 가지고 있다
  • 특정 인증 메커니즘에서 요청의 추가적인 정보를 인증 객체에 추가할 때 사용할 수 있으며 Authentication 객체와 함께 사용된다

AuthenticationDetailsSource

  • Authentication -> Details 저장하는 역할을 한다
  • 인증 과정 중에 Authentication 객체에 세부 정보(WebAuthenticationDetails)를 제공하는 소스 역할을 한다.
  • WebAuthenticationDetails 객체를 생성하는 데 사용되며 인증 필터에서 참조한다

인증상세 구현

  1. view에서 로그인시 header로 secret key를 보내준다
profile
하루 일지 보단 행동 고찰 과정에 대한 개발 블로그

0개의 댓글

관련 채용 정보