UserDetails
@Getter
public class UserAccount extends User {
private Account account;
public UserAccount(Account account) {
super(account.getNickname(), account.getPassword(),
List.of(new SimpleGrantedAuthority("ROLE_USER")));
this.account = account;
}
}
해당 UserDetails를 Principal로 AuthenticationToken을 Security Context에 저장하고 Thyemleaf Extras를 통해 Security Context에 접근할 수 있다.
View에서 Context 바로 접근
Controller
@Controller
public class MainController {
@GetMapping("/")
public String home(){
return "index";
}
}
컨트롤러에서 view로 아무것도 넘겨주지 않아도 인증후의 요청은 JSESSOINID를 들고 있기에 FilterSecurityInterceptor를 통해Security Context의 유저 정보는 유지된다.
View
// index,html - Nav bar
<svg th:if="${#strings.isEmpty(account?.profileImage)}" th:data-jdenticon-value="${#authentication.name}"
width="24" height="24" class="rounded border bg-light"></svg>
<img th:if="${!#strings.isEmpty(account?.profileImage)}" th:src="${#authentication.principal.profileImage}"
width="24" height="24" class="rounded border"/>
컨트롤러에서 따로 유저에 대한 정보를 넘기지 않아도 View에서 바로 Context에 접근할 수 있다.
Controller가 Context에 접근해서 Model로 넘기기
Controller
컨트롤러에서 컨텍스트에 접근하는 @AuthenticationPrincipal을 붙인 @CurrentAccount를 사용해서 로그인 중이면 account 객체를, 로그인 하지 않았다면 null을 넘겨준다.
@Controller
public class MainController {
@GetMapping("/")
public String home(@CurrentAccount Account account, Model model){
if(account != null){
model.addAttribute(account);
}
return "index";
}
View
// index.html - nav bar
<svg th:if="${#strings.isEmpty(account?.profileImage)}" th:data-jdenticon-value="${#authentication.name}"
width="24" height="24" class="rounded border bg-light"></svg>
<img th:if="${!#strings.isEmpty(account?.profileImage)}" th:src="${account.profileImage}"
width="24" height="24" class="rounded border"/>
이유
1. Thymeleaf View는 템플릿의 역할, 컨트롤러는 비즈니스 로직을 처리하는 역할을 담당, 역할의 분리
2. 유저정보를 Model로 View로 넘김으로서 컨트롤러는 인증의 유무에 따라 다른 비즈니스 로직을 처리가능
3. 유저정보는 민감정보일 수 있고 접근 제어 및 보안 정책을 적용함으로 View에서 접근하지 않게 해서 보안강화
4. Model을 통해 데이터를 전달하면 같은 데이터를 여러개의 View에서 재사용할 수 있어 데이터의 일관성과 중복제거 가능
참고
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-JPA-%EC%9B%B9%EC%95%B1/dashboard