2017-12-21 1 views
-1

세션에서 일부 사용자 정보에 액세스하고 싶습니다. 나는 loadUserByUsername (문자열 사용자 이름) 메서드를 재정 의하여 봄 보안 및 사용자 지정 인증을 사용하고 있습니다.스프링 보안 컨트롤러를 사용하여 Spring의 컨트롤러에서 UserDetails 객체에 액세스하기

사용자를 반품하고 나의 컨트롤러 내에서 액세스하고 싶습니다. 주체 개체를 시도했지만 내 ESecurityUser 개체의 companyId 필드에 연결할 수 없습니다.

어떤 도움을 주시면 감사하겠습니다 ..

@Override 
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 

    ESecurityUser user = new ESecurityUser(); 
    user.setUsername("hello"); 
    user.setPassword("world"); 
    user.setCompanyId(199); 

    Set<EAuthority> authorities = new HashSet<EAuthority>(); 
    EAuthority authority = new EAuthority(); 
    authority.setAuthority("ROLE_ADMIN"); 
    authorities.add(authority); 

    user.setAuthorities(authorities);; 

    return user; 
} 

샘플 컨트롤러 코드

@RequestMapping("") 
    public String toPeriodicAdReport(@ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper, 
      Model model,Principal principal) { 

     //What to write here so that i can access to authenticated user`s companyId field.. 

     return "Test"; 
    } 
+1

ESecurityUser 사용자 = (ESecurityUser) 주요; – brub

+1

@brub 안녕하세요, 저는 시도했지만 예외가 생겼습니다 .. org.springframework.security.authentication.UsernamePasswordAuthenticationToken은 tr.com.simroll.ada.rvm.report.entity.ESecurityUser'로 캐스팅 될 수 없습니다 – rematnarab

+0

이것은 비슷하게 보입니다 : https://stackoverflow.com/questions/12078404/org-springframework-security-core-userdetails-user-cannot-be-cast-to-myuser – brub

답변

1

직접 ESecurityUser에 액세스 할 수있는 주석 @AuthenticationPrincipal를 사용할 수 있습니다.

@RequestMapping("") 
public String toPeriodicAdReport(@ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper, 
     Model model, @AuthenticationPrincipal ESecurityUser principal) { 
    principal.getCompanyId(); 
    return "Test"; 
} 
0
ESecurityUser e = (ESecurityUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 

이 나를 위해 노력하고 있습니다 ..

1

당신했다 멀지 ...

Principal 컨트롤러 메서드에 전달 된 SpringMVC 기계는를 식별하는 Authentication 토큰입니다 사용자. 당신은 당신이에서 반환 된 ESecurityUser를 추출하기 위해 getDetails() 방법을 사용해야합니다 loadUserByUsername

귀하의 코드가 될 수 :

@RequestMapping("") 
    public String toPeriodicAdReport(@ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper, 
      Model model,Principal principal) { 

     ESecurityUser user = (ESecurityUser) ((Authentication) principal).getDetails(); 

     // stuff... 
     return "Test"; 
} 
관련 문제