-
spring security - Authentication, UserDetails, OAuth2User / 예시JAVA/Spring(Springboot) 2021. 8. 8. 20:47728x90
Spring Security를 사용하여 로그인하는 경우에는 Session영역에 Authentication 정보를 저장해둔다.
Authentication 은 컨트롤러 등에서 User에 대한 정보를 가져올 때 사용이 되는데,
사용자가 로그인 한 방식에 따라서 Authentication의 구현체가 달라진다.
- UserDetails : 사용자가 일반적(id, pw입력)으로 로그인 한 경우
- OAuth2User : Auth 로그인 한 경우 (ex- 구글, 카카오 등)그럼 컨트롤러에서 session에 담긴 사용자 정보를 들고 올때 로그인 방식에 상관없이 한 번에 가져올 수 있는 방법이 있을까? 답은 가능하다!
보통 SpringSecurity로 로그인을 구현할 때 UserDetails 를 먼저 구현하는 경우가 많다.
이 UserDetails를 구현하는 클래스에 OAuth2User도 구현하게 만들면 같은 클래스로 DI 받아서 사용할 수 있다.@ToString @Getter @Setter public class SecurityUser implements UserDetails, OAuth2User { private Long id; private String loginId; private String password; private String role; private Collection<? extends GrantedAuthority> authorities; ...
위 코드 처럼 SecurityUser 클래스로 일반 로그인, OAuth2 로그인 정보를 담을 수 있다.
컨트롤러에서 사용
@GetMapping("/reviewList") public String reviewList(@AuthenticationPrincipal SecurityUser securityUser) { Long userId = securityUser.getId(); return "reviewList"; }
728x90728x90'JAVA > Spring(Springboot)' 카테고리의 다른 글
[Spring] PRG(Post-Redirect-Get) 할 때 PathVariable, Url Encoding 신경쓰기 - RedirectAttribute (0) 2023.02.21 Query dsl 프로젝트 설정 시 unable to load class 'com.mysema.codegen.model.type'. gradle 오류 해결 (2) 2022.02.08 git 에 있는 프로젝트 Intellij 에 clone 하기 (0) 2021.08.04 [Spring] @RestController / @RequestBody (0) 2021.08.01