Github 연동 구현 이유
Github 연동 구현 방법
이번에 구현한 프로젝트는 CSR(Client Side Rendering) 방식으로 이루어져 있어 Authorization Code Grant 방식을 Client(React)와 Server(Spring)에서 하는 역할을 일부 나누었다.
Step1 : React에서 Github(Authorization Server)에 authorization code요청
Step2 : Spring에서 Github(Authorization Server)에 access token을 요청 (httpclient, gson 패키지를 이용)
private String takeAccessToken(String authorizationCode)
throws URISyntaxException, IOException {
HttpPost httpPost = new HttpPost();
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json");
URI uri = new URIBuilder("https://github.com/login/oauth/access_token").build();
httpPost.setURI(uri);
httpPost.setConfig(getRequestConfig());
GithubRestClientDto.Request request
= new GithubRestClientDto.Request(clientId, clientSecret, authorizationCode);
httpPost.setEntity(new StringEntity(gson.toJson(request)));
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse httpResponse = httpClient.execute(httpPost);
String resultJson = EntityUtils.toString(httpResponse.getEntity());
GithubRestClientDto.Response response = gson.fromJson(resultJson, GithubRestClientDto.Response.class);
if (response.getAccess_token() == null){
throw new BusinessLogicException(ExceptionCode.NOT_NORMAL_AUTHORIZATION_CODE);
}
return response.getAccess_token();
}
Step3 : Github(Resource Server)에 유저 정보를 요청함
private GithubRestClientDto.UserInfo getGithubInfo(String accessToken) throws IOException {
HttpGet httpGet = new HttpGet("https://api.github.com/user");
httpGet.addHeader("Authorization","Bearer " + accessToken);
httpGet.setConfig(getRequestConfig());
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse httpResponse = httpClient.execute(httpGet);
String resultJson = EntityUtils.toString(httpResponse.getEntity());
GithubRestClientDto.UserInfo response = gson.fromJson(resultJson, GithubRestClientDto.UserInfo.class);
response.setProvider(clientId);
return response;
}
Github 로그인 방법 선택 이유
Github 로그인 방법