SecurityContextHolder와 Authentication

SecurityContextHolder

SecurityContext제공, 기본적으로 ThreadLocal을 사용한다

SecurityContext

Authentication 제공

Authentication

Principal과 GrantAuthority 제공, Principal이라는 정보를 Authentication이라는 객체에 담아서 관리

인증이 되면 Authentication 객체를 만들고 이를 SecurityContextHolder안에 넣어서 관리

디버거로 확인

SimpleService를 만들고 dashboard에서 메소드를 호출한다

@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();
    }
}
@GetMapping("/dashboard")
    public String dashboard(Model model, Principal principal) {
        model.addAttribute("message", "Hello " + principal.getName());
        sampleService.dashboard();
        return "dashboard";
    }

authntication의 경우 loginform으로 인증하면 UsernamePasswordAuthentication 타입이 되고 principal은 UserDetailsService에서 리턴한 타입이 된다