스프링에서 로그인 된 객체 이용하기
1. Principal
@Controller
public class MemberController {
private final MemberService memberService;
@GetMapping("/mypage")
@ResponseBody
public String showMyPage(Model model, Principal principal) {
Member member = memberService.findByUsername(principal.getName());
model.addAttribute("member", member);
return "/member/mypage";
}
}
2. Authentication
@Controller
public class MemberController {
private final MemberService memberService;
@GetMapping("/mypage")
@ResponseBody
public String showMyPage(Authentication authentication) {
Principal principal = (Principal) authentication.getPrincipal();
String username = principal.getName();
Member member = memberService.findByUsername(username);
model.addAttribute("member", member);
return "/member/mypage";
}
}
3. @AuthenticationPrincipal
CustomOAuth2User extends User > User extends UserDetails
public class CustomOAuth2User extends User implements OAuth2User {
...
@Override
public String getName() {
return getUsername();
}
}
@Controller
public class MemberController {
private final MemberService memberService;
@GetMapping("/mypage")
@ResponseBody
public String showMyPage(@AuthenticationPrincipal CustomOAuth2User user) {
String username = user.getName();
Member member = memberService.findByUsername(username);
model.addAttribute("member", member);
return "/member/mypage";
}
}
'프로젝트 & TIL > 일별 공부 기록 (백엔드 스쿨)' 카테고리의 다른 글
68일차 - 레디스, 쿠버네티스 준비 (0) | 2023.05.30 |
---|---|
67일차 - @SuperBuilder (0) | 2023.05.26 |
65일차 - 깃허브 협업, 아이콘 제작 (0) | 2023.05.24 |
64일차 - 젠킨스 설치, 파이프라인 프로젝트, 프로토타이핑 툴 (0) | 2023.05.23 |
62일차 - 젠킨스 개요 (0) | 2023.05.22 |