Account 객체 형변환 오류 문의드립니다
550
작성한 질문수 20
실전프로젝트 강의 듣고 있습니다.
접근권한 관련해서 오류가 있어서 문의 드립니다.
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 인턴이에요.
문제를 해결하기에 앞서, 에러 내용과 스택 트레이스를 함께 보내주시면 보다 정확한 답변을 드릴 수 있을 것 같아요. 하지만 가장 가능성이 높은 원인은 authentication.getPrincipal() 메서드가 Account 객체가 아닌 AccountContext 객체를 반환하기 때문이에요.
AccountContext는 Account와 GrantedAuthority를 가지고 있는 DTO(Data Transfer Object) 클래스로, Spring Security에서 사용되는 인증 객체나 권한 부여 객체를 담는 컨테이너 역할을 해요. 따라서 authentication.getPrincipal()의 반환값인 AccountContext를 Account 객체로 형변환할 수 없는 것이죠.
따라서 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 객체를 얻어와야 합니다. 그리고 이런 상황에서는 먼저 해당 클래스의 소스코드와 관련된 문서들을 살피는 것이 좋겠죠. 수고하세요!
시큐리티 공부 버전 질문
0
176
1
[해결 방법] MethodSecurityConfig.customMethodSecurityMetadataSource() 호출하지 않는 이슈
0
187
1
AbstractSecurityInterceptor.class.beforeInvocation()를 2번 실행하는 경우
0
178
1
강의 코드가 왜이렇게 뒤죽박죽인가요...
0
252
1
메인 페이지로 접속해도 login url로 리다이렉트가 되지 않습니다..
0
238
1
파라미터값이 넘어가지 않습니다 ....
0
375
1
security filterChain 설정 질문이 있습니다.
0
332
1
소스 부분 질문 드립니다.
0
210
2
섹션4 7번 강의 문제가 있는거 같네요.
0
345
2
파일이 수시로 이름이 바껴있네요 ㄷㄷ
0
306
1
HttpSessionSecurityContextRepository를 사용안하는 문제
0
557
2
error , exception 이 잘 안됩니다.
0
284
2
thymeleaf tag 질문합니다.
0
198
2
버전업하면서 deprecated된 것들이 너무많아요
0
478
1
spring security 패치 관련
0
437
1
모바일을 사용할때 토큰말고 세션
0
850
2
DB 연동한 인가 부분에 대한 질문입니다!
0
265
1
Ajax방식도 똑같이 Session방식을 사용하는건가요?
0
308
1
Config 파일 생성 시 질문이 있습니다.
0
228
1
강사님 몇일동안 구글 검색만 100개 했는데도 이유를 모르겠습니다..
1
433
2
403 에러 뜹니다.
0
813
2
login_proc의 존재에 대한 간략한 설명입니다
0
277
1
top.html에 로그인 링크를 만들어서 로그인을 해봤습니다
0
287
2
안녕하세요. DB에 저장될 때 이해 안 가는 값이 있어서 질문드립니다!
0
191
1





