본문 바로가기

프로젝트 & TIL/일별 공부 기록 (백엔드 스쿨)

66일차 - 스프링 로그인 된 객체 이용하기

스프링에서 로그인 된 객체 이용하기

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";
    } 
}