복잡하기 때문에 부분 부분 알아보고 나중에 합쳐 보자.
인증된 사용자 정보는 Principal이라고 한다.
이 정보를 Authentication 객체에 담아서 관리하고 그 밖을 또 두번 감싼다.
전역 데이터를 한번 사용해 보자.
@Service
public class SampleService {
public void dashboard() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Object principal = authentication.getPrincipal();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
Object credentials = authentication.getCredentials();
boolean authenticated = authentication.isAuthenticated();
}
}
Principal은 User타입인데 이 User는 우리가 UserDetailsService에서 리턴했던 객체이다.
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Account account = accountRepository.findByUsername(username);
if (account == null) {
throw new UsernameNotFoundException(username);
}
return User.builder()
.username(account.getUsername())
.password(account.getPassword())
.roles(account.getRole())
.build();
}
GrantedAuthority 컬렉션도 확인해 보자.
이 정보는 어디서 왔을까, 마찬 가지로 User를 만들때 넣어 주었다. ROLE_
은 자동으로 붙여준 것이다.
Principal이 가지고 있는 권한들을 나타내는 데이터이다.
credential은 없는데 이미 인증된 상태이기 때문에 필요가 없다.