HD

[구글] GOOGLE Oauth 로그인 API (2) 본문

API/GOOGLE

[구글] GOOGLE Oauth 로그인 API (2)

hunecenter 2019. 10. 24. 18:02
반응형

GOOGLE  Oauth 클라이언트ID를 생성 하였다면 해당 로그인 로직을 구현하겠습니다.

 

1.AccessToken 처리

	/**
	 * GOOGLE AccessToken 처리
	 */
	@Override
	public String getGoogleAccessToken(String authorize_code) {
		String access_Token = "";
		String reqURL = "https://www.googleapis.com/oauth2/v4/token";
		
	    try {
	        URL url = new URL(reqURL);
	        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	        
	        //POST 요청을 위해 기본값이 false인 setDoOutput을 true로
	        conn.setRequestMethod("POST");
	        conn.setDoOutput(true);
	        //POST 요청에 필요로 요구하는 파라미터 스트림을 통해 전송
	        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
	        StringBuilder sb = new StringBuilder();
	        sb.append("grant_type=authorization_code");
	        sb.append("&client_id=ClientId");
	        sb.append("&client_secret=ClientSecret");
	        sb.append("&redirect_uri=RedirectUri");
	        sb.append("&code="+authorize_code);
	        sb.append("&state=url_parameter");
	        bw.write(sb.toString());
	        bw.flush();
	        
	        //결과 코드가 200이라면 성공
	        int responseCode = conn.getResponseCode();
	        if(responseCode==200){
	            //요청을 통해 얻은 JSON타입의 Response 메세지 읽어오기
	            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	            String line = "";
	            String result = "";
	            
	            while ((line = br.readLine()) != null) {
	                result += line;
	            }
	            
	            //Gson 라이브러리에 포함된 클래스로 JSON파싱 객체 생성
	            JsonParser parser = new JsonParser();
	            JsonElement element = parser.parse(result);
	            System.out.println("result : "+result);
	            access_Token = element.getAsJsonObject().get("access_token").getAsString();
	          //refresh_Token = element.getAsJsonObject().get("refresh_token").getAsString();
	            br.close();
	            bw.close();
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    } 
	    
	    return access_Token;
	}

2. 회득한 AccessToken으로 유저정보 가져오기

	/**
	 * GOOGLE USER INFO
	 * @param access_Token
	 */
	@Override
	public void getGoogleUserInfo(String access_Token) {
		 //요청하는 클라이언트마다 가진 정보가 다를 수 있기에 HashMap타입으로 선언
	    HashMap<String, Object> googleUserInfo = new HashMap<>();
	    //String reqURL = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token="+access_Token;
	    String reqURL = "https://www.googleapis.com/userinfo/v2/me?access_token="+access_Token;
	    try {
	        URL url = new URL(reqURL);
	        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

	        //요청에 필요한 Header에 포함될 내용
	        conn.setRequestProperty("Authorization", "Bearer " + access_Token);

	        int responseCode = conn.getResponseCode();
	        System.out.println("responseCode : "+responseCode);
	        if(responseCode == 200){
		        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		        
		        String line = "";
		        String result = "";
		        
		        while ((line = br.readLine()) != null) {
		            result += line;
		        }
		        JsonParser parser = new JsonParser();
		        System.out.println("result : "+result);
		        JsonElement element = parser.parse(result);
		        
		        String name = element.getAsJsonObject().get("name").getAsString();
		        String email = element.getAsJsonObject().get("email").getAsString();
		        String id = "GOOGLE_"+element.getAsJsonObject().get("id").getAsString();
		        
		        googleUserInfo.put("name", name);
		        googleUserInfo.put("email", email);
		        googleUserInfo.put("id", id);
		        
		        System.out.println("login Controller : " + googleUserInfo);
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

3. Controller처리

feat.구글 같은경우 scope로 구글에 어떤 항목에 정보를 요청할지 목록을 정함으로 googlescopes 문서 참조 

https://developers.google.com/identity/protocols/googlescopes

 

OAuth 2.0 Scopes for Google APIs  |  Google ID 플랫폼  |  Google Developers

This document lists the OAuth 2.0 scopes that you might need to request to access Google APIs, depending on the level of access you need. Sensitive scopes require review by Google and have a sensitive indicator on the Google Cloud Platform (GCP) Console's

developers.google.com

	/**
	 * sns Login
	 */
	@RequestMapping( "/index" )
	public String view(
			ModelMap model ) {
		
		String googleUrl = "https://accounts.google.com/o/oauth2/auth?client_id=client_id&redirect_uri=redirect_uri&access_type=offline&response_type=code&scope=email%20profile&state=url_parameter";
		model.addAttribute( "googleUrl", googleUrl );
		return "/index";
	}


	/**
	 * GOOGLE Login 
	 * @param code
	 * @throws IOException 
	 */
	@RequestMapping( "/googleLogin" )
	public void  googleLogin(
			@RequestParam("code") String code,
			HttpServletResponse response
			) throws IOException {
		String access_Token = snsLoginService.getAccessToken(code);
		
        //리다이렉트 url
		String referer = (String)request.getHeader("REFERER")!=null? (String)request.getHeader("REFERER") : "http://localhost:8080";
		
		snsLoginService.getUserInfo(access_Token);
		
		response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        //Login Popup창 닫고 page referer url로 새로고침
        out.println("<script>window.close(); opener.parent.location="+"'"+referer+"'"+";</script>");
        out.flush();
	}

4.index.jsp

<a id="custom-login-btn" href="javascript:void(0);" onclick="window.open('${googleUrl}','googleLogin','width=430,height=500,location=no,status=no,scrollbars=yes');"">
	<img src="/images/btn_google_signin_dark_normal_web.png" width="300"/>
</a>

 

반응형

'API > GOOGLE' 카테고리의 다른 글

[구글] GOOGLE Oauth 로그인 API (1)  (0) 2019.10.24
Comments