스프링 시큐리티를 사용하다가 사용자 정보를 뽑아서 써야되는데 참 갑갑할때가 있다.
내가 만든 것도 아니라서 어디서 뽑아다가 써야될지도 잘 모르겠고
스프링 시큐리티 너무 복잡해서 어떻게 찾을지도 잘 모르겠고 그럴때가 많다.
google search keyword : spring security get current user details
스택오버플로우가 글이 날라가지는 않을 것 같지만 혹시나 해서 그냥 퍼놔야겠다.
1. SpringSecurityContextHolder를 사용하는 방법
1 2 3 4 5 6 7 8 9 10 |
public static User getCurrentUser() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal() if (principal instanceof MyUserDetails) return ((MyUserDetails) principal).getUser(); // principal object is either null or represents anonymous user - // neither of which our domain User object can represent - so return null return null; } |
2. 뭔지 잘 모르겠는데 좋아보이는 방법 – 토큰을 집어오는것같다.
1 2 3 4 5 6 7 8 9 |
@Controller public class KnoteController { @RequestMapping(method = RequestMethod.GET) public java.lang.String list(Model uiModel, UsernamePasswordAuthenticationToken authToken) { if (authToken instanceof UsernamePasswordAuthenticationToken) { user = (User) authToken.getPrincipal(); } ... } |
3. User는 아니지만 UserPrincipal을 가져오는 방법
1 2 3 4 5 |
private String principal; @Principal public setPrincipal(String principal){ this.principal=principal; } |