본문 바로가기

Spring Boot

[Google API + Springboot] 구글 계정으로 로그인 처리방법

반응형

1. Google API Console에서 새 프로젝트를 만듭니다.
2. 프로젝트에 대해 Google 로그인 API를 사용하도록 설정합니다.
3. Java용 Google API Client Library를 다운로드합니다.
4. Google API Client Library를 사용하도록 Spring Boot 응용 프로그램을 구성합니다.
5. 프로그램 UI에 로그인 버튼을 추가합니다.
6. 서버측 논리를 구현하여 권한 부여 코드를 액세스 토큰으로 교환합니다.
7. 액세스 토큰을 사용하여 사용자의 Google 계정 정보에 액세스합니다.

*다음 종속성을 pom.xml 파일에 추가합니다.

<dependency>
  <groupId>com.google.apis</groupId>
  <artifactId>google-api-services-oauth2</artifactId>
  <version>v1-rev75-1.25.0</version>
</dependency>

 

*application.properties 파일에 다음을 추가합니다.

google.client.client-id=<your-client-id>
google.client.client-secret=<your-client-secret>
google.client.access-token-uri=https://oauth2.googleapis.com/token
google.client.user-authorization-uri=https://oauth2.googleapis.com/auth
google.client.token-name=oauth_token
google.client.authentication-scheme=query
google.client.client-authentication-scheme=form

 

*GoogleAuthController라는 새 클래스를 만듭니다.

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@Controller
public class GoogleAuthController {

  private HttpTransport transport = new NetHttpTransport();
  private JsonFactory jsonFactory = new JacksonFactory();

  @Value("${google.client.client-id}")
  private String clientId;

  @Value("${google.client.client-secret}")
  private String clientSecret;

  @Value("${google.client.access-token-uri}")
  private String accessTokenUri;

  @Value("${google.client.user-authorization-uri}")
  private String userAuthorizationUri;

  @RequestMapping("/oauth2callback")
  public String handleGoogleCallback(@RequestParam("code") String code) throws IOException {
    GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
        transport, jsonFactory, clientId, clientSecret, code, userAuthorizationUri).execute();
    GoogleIdToken idToken = tokenResponse.parseIdToken();
    String email = idToken.getPayload().getEmail();
    // Store the email address in your database, associate it with a user
    // ...
  }
}
반응형