Skip to content

Commit

Permalink
Merge pull request #107 from Developer-Wikis/feat/githubLogin
Browse files Browse the repository at this point in the history
Feat : 깃허브 로그인 테스트 완료(컨트롤러 부분에 하드 코딩 추후 구조 변경 할것)
  • Loading branch information
jhdl0157 authored Nov 30, 2022
2 parents 6509fe8 + 336effd commit bd00e9d
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,22 +1,85 @@
package com.developer.wiki.oauth.controller;

import com.developer.wiki.common.exception.BadRequestException;
import com.developer.wiki.oauth.dto.GitHubOauthToken;
import com.developer.wiki.oauth.dto.GoogleOAuthToken;
import com.developer.wiki.oauth.dto.GoogleResponseDto;
import com.developer.wiki.oauth.service.OauthService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/oauth")
public class OauthController {
private final OauthService oauthService;

private final RestTemplate restTemplate;

private final ObjectMapper objectMapper;
@Value("${custom.github.client-id}")
private String GITHUB_CLIENT_ID;

@Value("${custom.github.client-secret}")
private String GITHUB_CLIENT_SECRET;

@GetMapping()
public String Code(@RequestParam(value = "code")String code) throws JsonProcessingException {
System.out.println("코드 값임당 "+code);
String GOOGLE_TOKEN_REQUEST_URL="https://github.com/login/oauth/access_token";
RestTemplate restTemplate=new RestTemplate();
Map<String, Object> params = new HashMap<>();
params.put("code", code);
params.put("client_id", GITHUB_CLIENT_ID);
params.put("client_secret", GITHUB_CLIENT_SECRET);
params.put("redirect_uri", "http://localhost:8080/api/v1/oauth");
ResponseEntity<String> responseEntity;
try {
responseEntity=restTemplate.postForEntity(GOOGLE_TOKEN_REQUEST_URL,params,String.class);
System.out.println("엑세스 토큰 임당 "+responseEntity.getBody());
}catch (RestClientException e){
e.printStackTrace();
throw new BadRequestException(String.format("인가코드로 구글의 AccessToken을 발급하지 못했습니다. code : %s, redirectUrl : %s, 오류 내용 : %s",code,"redirectUrl",e.getMessage()));
}
String[] resList=responseEntity.getBody().split("&");
String[] token=resList[0].split("=");
System.out.println("토큰의 값은 : "+token[1]);
String GOOGLE_USERINFO_REQUEST_URL="https://api.github.com/user";
//header에 accessToken을 담는다.
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization","Bearer "+token[1]);

//HttpEntity를 하나 생성해 헤더를 담아서 restTemplate으로 구글과 통신하게 된다.
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(headers);
try {
ResponseEntity<String> response=restTemplate.exchange(GOOGLE_USERINFO_REQUEST_URL, HttpMethod.GET,request,String.class);
System.out.println("response.getBody() = " + response.getBody());
return response.getBody();
}catch (RestClientException e){
throw new BadRequestException("구글 AccessToken을 으로 사용자 정보를 가져오지 못했습니다.");
}
}
private GitHubOauthToken getAccessToken(ResponseEntity<String> response) throws JsonProcessingException {
System.out.println("response.getBody() = " + response.getBody());
GitHubOauthToken gitHubOauthToken= objectMapper.readValue(response.getBody(),GitHubOauthToken.class);
return gitHubOauthToken;
}
@GetMapping("/google/userinfo")
public ResponseEntity<GoogleResponseDto> getGoogleUserInfo(@RequestParam("code") String code,@RequestParam("redirectUrl")String redirectUrl) throws IOException {
System.out.println(">> 소셜 로그인 API 서버로부터 받은 code :"+ code);
Expand All @@ -30,4 +93,11 @@ public ResponseEntity<String> getGoogleUrl(@RequestParam String url, HttpServlet
//response.sendRedirect(redirectUrl);
return ResponseEntity.ok(redirectUrl);
}
@GetMapping("/github/userinfo")
public ResponseEntity<String> getGitHubUserInfo(@RequestParam("code") String code,@RequestParam("redirectUrl")String redirectUrl) throws IOException {
System.out.println(">> 소셜 로그인 API 서버로부터 받은 code :"+ code);
System.out.println(">> 소셜 로그인 API 서버로부터 받은 url :"+ redirectUrl);
//GoogleResponseDto GoogleUser = oauthService.oAuthLogin(code,redirectUrl);
return new ResponseEntity<>(code, HttpStatus.OK);
}
}
14 changes: 14 additions & 0 deletions src/main/java/com/developer/wiki/oauth/dto/GitHubOauthToken.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.developer.wiki.oauth.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@AllArgsConstructor
@Getter
@Setter
public class GitHubOauthToken {
private String access_token;
private String scope;
private String token_type;
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ public String googleInitUrl(String url) {

public ResponseEntity<String> requestAccessToken(String code,String redirectUrl) {
String GOOGLE_TOKEN_REQUEST_URL="https://oauth2.googleapis.com/token";
RestTemplate restTemplate=new RestTemplate();
Map<String, Object> params = new HashMap<>();
params.put("code", code);
params.put("client_id", GOOGLE_SNS_CLIENT_ID);
Expand All @@ -79,7 +78,6 @@ public GoogleOAuthToken getAccessToken(ResponseEntity<String> response) throws J
System.out.println("response.getBody() = " + response.getBody());
GoogleOAuthToken googleOAuthToken= objectMapper.readValue(response.getBody(),GoogleOAuthToken.class);
return googleOAuthToken;

}

public ResponseEntity<String> requestUserInfo(GoogleOAuthToken oAuthToken) {
Expand Down
3 changes: 3 additions & 0 deletions src/main/resources/application-oauth.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,8 @@ custom:
scope : https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email
client-id: ENC(Stk5BNqlTPDUykrnPM0g7bOZ+T/c4kAa191scAucdBOZHq9Eq8eLFTbtFhoBeNRKoMMEXGfUC6MHHFxk4DqReqRiSNpue7u7XblRjluFdL9VKbQxsRH0Aw==)
client-secret: ENC(zJ/hEIdsY55cmXyEk8M2SYJ6RUGhxJByLc1whUj6IAfh9ZwWmYSDkdtI5k8jQPE9)
github:
client-id : ENC(PlT5DdeWhTqT/jyP81Ao4w5z53UDZ2t6cN7V0O+xtaI=)
client-secret : ENC(+xbNlumfURi7aixRrtMODILbhQY800HSVSz6/nIiOYLuTbbhcRvesFJsj45GhxA3HddjrOsUaCQ=)
jwt:
secretKey: ENC(4eL6R6/CT+2w1ss8z9kbLCGT+TLF4JrAw4HATFWQGA0ZVg53roc2Ej/OOKsI5G/9kBSzPV8dZ5l84UNnKMF8Iw==)

0 comments on commit bd00e9d

Please sign in to comment.