스프링 시큐리티 authentication 가져오기

greenTea·2023년 3월 22일

Authentication DI 받기

스프링 시큐리티에는 authentication이라는 인증 객체가 있다. authentication을 통해 로그인 과정을 처리할 수 있다. 이 때 authentication을 자동 주입 받을 수 있는데 아래는 그 예이다.😊

Authentication 객체 이용

@GetMapping("/home")
public String getUser(Authentication authentication) {
    return "home";
}

또는 Security context holder를 이용 할 수도 있다.

SecurityContextHolder 이용


@GetMapping("/home")
public String getUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    
    return "home";
}

위 코드는 authentication 객체를 가져온다는 공통점이 있지만 차이점이 있다.
1. 1번 코드는 인증이 완료된 객체만을 가져 올 수 있다. 만약 인증전에 들어간다면 null을 반환 한다.

  1. 반대로 2번 코드는 인증 전에도 가져올 수 있게 되어 있다. 스프링 시큐리티는 인증 전에 authentication객체를 만들어서 뒤 필터등의 과정에서 사용하기 위해 security context holder에 저장하기 때문에 꺼내 올 수 있다.😂

1번 코드에서 authentication을 꺼내 왔다면 바로 쓸 수 있지만 보통은 UserDetail로 캐스팅 해주어서 사용해야 편하다. 그러나 @AuthenticationPricipal를 사용한다면 캐스팅 없이 바로 사용 할 수 있다.👍

@AuthenticationPricipal 이용

@GetMapping("/home")
public String getUser(@AuthenticationPricipal UserDetail user) {
   
   return "home";
}

😎Authentication을 상속받은 것들은 다 가능함으로 OAuth2User, OIdcUser, UserDetail, UsernamepasswordToken등으로도 받을 수 있다.

주의 사항

만약 formlogin방식으로 인증에 성공한 authentication객체에서 getPrincipal()을 통해 가져 올때 타입을 OAuth2User로 가져오면 타입변환예외가 터지므로 주의해야 한다.

profile
greenTea입니다.

0개의 댓글