SecurityContext
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
@AuthenticationPrincipal spring.security.User user
@GetMapping
public ResponseEntity queryEvents(Pageable pageable,
PagedResourcesAssembler<Event> assembler,
@AuthenticationPrincipal User user) {
Page<Event> page = this.eventRepository.findAll(pageable);
PagedResources pagedResources = assembler.toResource(page, e -> new EventResource(e));
pagedResources.add(new Link("/docs/index.html#resources-events-list").withRel("profile"));
if (user != null) {
pagedResources.add(linkTo(EventController.class).withRel("create-event"));
}
return ResponseEntity.ok(pagedResources);
}
Account로 바꾸자
어댑터 클래스
public class AccountAdapter extends User {
private Account account;
public AccountAdapter(Account account) {
super(account.getEmail(), account.getPassword(), authorities(account.getRoles()));
this.account = account;
}
private static Collection<? extends GrantedAuthority> authorities(Set<AccountRole> roles) {
return roles.stream()
.map(r -> new SimpleGrantedAuthority("ROLE_" + r.name()))
.collect(Collectors.toSet());
}
public Account getAccount() {
return this.account;
}
}
AccountService 수정
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Account account = accountRepository.findByEmail(username)
.orElseThrow(() -> new UsernameNotFoundException(username));
return new AccountAdapter(account);
//return new User(account.getEmail(), account.getPassword(), authorities(account.getRoles()));
}