Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- FCM
- 개발자도구
- Was
- 브라우저
- 접근장치
- WINDOW11
- dbms
- ua-parser
- AES
- web server
- Oracle
- window10
- Java
- Login
- User-Agent
- eGov
- 알고리즘
- TailMe
- URLRewirte
- Tomcat
- @Scheduled
- 암호화
- Firebase
- db
- scheduled
- JEUS
- WebtoB
- mysql
- 물리적주소
- programmers
Archives
- Today
- Total
HD
[구글] GOOGLE Oauth 로그인 API (2) 본문
반응형
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
/**
* 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