[Spring Security] 컨트롤러에서 사용자 정보 얻어오기

메서드 인자 (Principal)

1
2
3
4
@GetMapping("/index")
public void index(Pricipal principal) {
System.out.println("username = " + principal.getName());
}

메서드 인자 (Authentication)

1
2
3
4
5
6
@GetMapping("/index")
public void index(Authentication authentication) {
UserDetails userDetails = (UserDetails)authentication.getPrincipal();
System.out.println("username = " + userDetails.getUsername());
System.out.println("role = " + userDetails.getAuthorities().stream().map(r -> String.valueOf(r)).collect(Collectors.joining(",")));
}

Bean

1
2
3
4
5
6
7
@GetMapping("/index")
public void index(Pricipal principal) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetails userDetails = (UserDetails)principal;
String username = principal.getUsername();
String password = principal.getPassword();
}

@AuthenticationPrincipal

Spring Security 3.2부터 지원하며 UserDetails를 구현한 클래스와 UserDetailsService를 구현한 서비스가 있을 때 정상동작을 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Controller
public class IndexController {
@GetMapping("/index")
public void index(@AuthenticationPrincipal Member member) {
System.out.println("username = " + member.getUsername());
}
}

@Entity
public Member implements UserDetails {
// ...
}

@Service
public class UserSevice implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return memberRepository.findByUsername(username);
}
}

댓글

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×