• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

Account 객체 형변환 오류 문의드립니다

23.03.14 15:01 작성 23.03.14 15:04 수정 조회수 410

0

실전프로젝트 강의 듣고 있습니다.

접근권한 관련해서 오류가 있어서 문의 드립니다.

authentication.getPrincipal() 을 Account 로 형변환시 오류가 발생하네요.

값들을 찍었을 때 아래와 같이 나옵니다.

 

1. accountContext.getAccount() : Account(Id=1, username=user, password={bcrypt}$2a$10$Uh4Z9AZmSNzdke9QgvawxODb0pK2vwV2xzrMS9EgXGzICO54WoIU2, email=abc@gmail.com, age=99, role=ROLE_USER)

2. authentication.getPrincipal() : io.security.corespringsecurity.security.service.AccountContext [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]]

 

 getPrincipal() 에 관련없는 텍스트가 나와서 그런지 잘모르겠군요. => 'io.security.corespringsecurity.security.service.AccountContext'

어떤 이유에서 오류가 발생하는지 답변 부탁드려요~

 

 

 

@GetMapping(value={"/denied", "/api/denied"})

public String accessDenied(@RequestParam(value = "exception", required = false) String exception, Model model){

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

// 형 변환이 안되네요.

Account account = (Account) authentication.getPrincipal();

model.addAttribute("username", account.getUsername());

model.addAttribute("exception", exception);

return "user/login/denied";

}

 

답변 1

답변을 작성해보세요.

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.05.24

안녕하세요, 인프런 AI 인턴이에요.

문제를 해결하기에 앞서, 에러 내용과 스택 트레이스를 함께 보내주시면 보다 정확한 답변을 드릴 수 있을 것 같아요. 하지만 가장 가능성이 높은 원인은 authentication.getPrincipal() 메서드가 Account 객체가 아닌 AccountContext 객체를 반환하기 때문이에요.

AccountContextAccountGrantedAuthority를 가지고 있는 DTO(Data Transfer Object) 클래스로, Spring Security에서 사용되는 인증 객체나 권한 부여 객체를 담는 컨테이너 역할을 해요. 따라서 authentication.getPrincipal()의 반환값인 AccountContextAccount 객체로 형변환할 수 없는 것이죠.

따라서 AccountContext에서 getAccount() 메서드를 호출하여 Account 객체를 얻어와야 해요. 코드를 아래와 같이 수정하면 됩니다.

@GetMapping(value={"/denied", "/api/denied"})
public String accessDenied(@RequestParam(value = "exception", required = false) String exception, Model model){
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    AccountContext accountContext = (AccountContext) authentication.getPrincipal();
    Account account = accountContext.getAccount();

    model.addAttribute("username", account.getUsername());
    model.addAttribute("exception", exception);
    return "user/login/denied";
}

요약하면, authentication.getPrincipal()의 반환값이 AccountContext이기 때문에 Account 객체로 형변환할 수 없으며, AccountContext에서 Account 객체를 얻어와야 합니다. 그리고 이런 상황에서는 먼저 해당 클래스의 소스코드와 관련된 문서들을 살피는 것이 좋겠죠. 수고하세요!