본문 바로가기
Back/Spring

[Spring/Security] Authentication 객체가 가질 수 있는 2가지 타입

by 오엥?은 2023. 6. 23.
반응형

📌 Authentication 객체가 가질 수 있는 2가지 타입

◽ 구글 로그인 버튼 클릭 → 구글 로그인창 → 로그인 완료 → code 리턴(OAuth-Client 라이브러리) → AccessToken 요청 

◽ userRequest 정보 → loadUser 함수 호출 → 회원 프로필을 구글로 부터 받음

 

 

✔ Controller

@GetMapping("/test/login")
public @ResponseBody String testLogin(
		Authentication authentication,
		@AuthenticationPrincipal PrincipalDetails userDetails) { // DI(의존성주입)
    PrincipalDetails principalDetails = (PrincipalDetails) authentication.getPrincipal();
    System.out.println("authentication : " + principalDetails.getUser());
    // 여기서 principalDetails.getUser는 Object 타입

    System.out.println("userDetails: " + userDetails.getUser());
    return "세션 정보 확인하기";
}

* @AuthenticaionPrincipal이라는 어노테이션을 통해서 세션 정보에 접근할 수 있다.

 

1) Authenticaion을 DI(Dependency Injection)에서 다운캐스팅 과정을 거친 후, principalDetails.getUser()를 찾을 수 있다.

2) @AuthenticaionPrincipal 어노테이션을 통해서 userDetails.getUser()를 찾을 수 있다.

 

1), 2) 는 둘 다 같은 정보를 가지고 있다.

 

 

2023.06.23 - [Back/Spring] - [Spring/Security] 구글 로그인 준비

 

[Spring/Security] 구글 로그인 준비

📌 구글 로그인 ✔ Google Api Console 접속 https://console.cloud.google.com Google 클라우드 플랫폼 로그인 Google 클라우드 플랫폼으로 이동 accounts.google.com ◽ 새로운 프로젝트 만들기 ① 프로젝트를 만들기

pickmeplease.tistory.com

2023.06.23 - [Back/Spring] - [Spring/Security] 구글 회원 프로필 정보 받아오기

 

[Spring/Security] 구글 회원 프로필 정보 받아오기

📌 구글 회원 프로필 정보 받아오기 ✔ 구글 로그인이 완료된 뒤의 후처리 1) 코드받기 (인증) 2) 액세스토큰 (권한) - 액세스 토큰을 받으면 Security 서버가 구글에 로그인한 사용자의 정보에 접근

pickmeplease.tistory.com

 

그런데 위와 같은 방법으로 만들어 놓은 구글 로그인으로 로그인을 하면, 500 에러가 뜬다.

 

PrincipalDetails principalDetails = (PrincipalDetails) authentication.getPrincipal();

이 부분에서 에러가 나는 것이다.

 

 

@GetMapping("/test/oauth/login")
public @ResponseBody String testOAuthLogin(
		Authentication authentication) { // DI(의존성주입)
        
    OAuth2User oauth2User = (OAuth2User) authentication.getPrincipal();
    System.out.println("authentication : " + oauth2User.getAttributes());
    
    return "OAuth세션 정보 확인하기";
}

Controller 에서 위에 작성해 뒀던 testLogin을 복사하여 testOAuthLogin을 만든다.

에러가 난 PrincipalDetails 대신 OAuth2User로 다운캐스팅을 하도록 한다.

 

{

sub={구글에 회원가입한 아이디},
name=손흥민, 
given_name=흥민,
family_name=손,
picture={사용자 프로필사진 주소},
email={사용자 이메일}
email_verified=true,
local=ko

}

그럼 밑줄인 sout이 위 정보를 출력한다.

 

 

 

참고 : 인프런 - 스프링부트 시큐리티 & JWT 강의 (최주호)

반응형