본문 바로가기
프로그래밍/API

[구글 로그인 API] 자바 스프링 Backend 인증

by 밍구몬 2019. 11. 25.

이번 글에서는 구글 로그인 API를 이용하여 백엔드 인증하는 법을 설명하겠습니다.

 

https://developers.google.com/identity/sign-in/web/backend-auth

위 사이트에 백엔드 인증하는 방법이 영문으로 소개되어 있습니다.

 

백엔드 인증을 하는 방법으로는 두가지가 있는데,

첫 번째로 Using a Google API Client Library (구글 라이브러리 사용)

두 번째로 Calling the tokeninfo endpoint (토큰인포 엔드 포인트 호출)

가 있습니다.

 

처음에는 1번 방법으로 해보려 했으나, 설명이 제대로 나와있지 않아 2번 방법으로 하였습니다.

 

Calling the tokeninfo endpoint

토큰 ID를 검증하는 쉬운  방법은 tokeninfo end point를 이용하는 것이지만, 약간의 대기 시간과 네트워크 오류 가능성이 있다고 합니다.

 

요청하는 방법은 간단합니다.

웹에서 요청받은 tokenId를 https://oauth2.googleapis.com/tokeninfo 의 url로 보내주기만 하면 됩니다.

 

Script

	function attachSignin(element) {
	    auth2.attachClickHandler(element, {},
	        function(googleUser) {
	    		var id_token = googleUser.getAuthResponse().id_token;
	    		
	    		var xhr = new XMLHttpRequest();
	    		xhr.open('POST', '백엔드 주소');
	    		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    		xhr.onload = function() {
	    		  console.log('Signed in as: ' + xhr.responseText);
	    		};
	    		xhr.send('idtoken=' + id_token);
	    		
	        }, function(error) {
	          console.log(JSON.stringify(error, undefined, 2));
	        });
	  }

 

Backend

	@PostMapping(value="/googleLogin.do", produces="application/x-www-form-urlencoded")
	@ResponseBody
	public String googleLogin(@RequestBody String param) {
		
		BufferedReader in  = null;
		InputStream is = null;
		InputStreamReader isr = null;
		JSONParser jsonParser = new JSONParser();
        
		String userId = null;
		
		try {
			String idToken = param.split("=")[1];
			
			String url = "https://oauth2.googleapis.com/tokeninfo";
			url += "?id_token="+idToken;
			
			URL gUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) gUrl.openConnection();

			is = conn.getInputStream();
			isr = new InputStreamReader(is, "UTF-8");
			in = new BufferedReader(isr);
			

			JSONObject jsonObj = (JSONObject)jsonParser.parse(in);

			userId = jsonObj.get("sub").toString();
			String name = jsonObj.get("name").toString();
			String email = jsonObj.get("email").toString();
			String imageUrl = jsonObj.get("picture").toString();
			
			System.out.println(userId);
			System.out.println(name);
			System.out.println(email);
			System.out.println(imageUrl);
			
		}catch(Exception e) {
			System.out.println(e);
		}
		
		return userId;
	}

 

이제 이 정보를 가지고 DB에 저장하거나 세션을 만드시면 됩니다.