leeheejo 5 vuotta sitten
vanhempi
commit
7f7a377098

+ 62 - 17
java/com/icontrols/oauth/controller/OAuthController.java

@@ -10,8 +10,10 @@ import java.util.Base64.Encoder;
 import java.util.List;
 import java.util.Random;
 
+import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
+import org.json.JSONObject;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -44,6 +46,7 @@ import com.icontrols.oauth.repo.ComplexInfoRepository;
 import com.icontrols.oauth.utils.AES256Util;
 import com.icontrols.oauth.utils.DanziAuthUtils;
 import com.icontrols.oauth.utils.JWTUtils;
+import com.sun.net.httpserver.HttpServer;
 
 @RestController
 @RequestMapping(value = "/api/oauth2")
@@ -166,7 +169,7 @@ public class OAuthController {
 		String endPoint = clientInfo.getEndPoint();
 
 //		String url = "http://" + complex + ":8002/kakao/auth";
-		String url = "http://" + complex + endPoint+"/auth";
+		String url = "http://" + complex + endPoint + "/auth";
 
 		logger.info(url);
 
@@ -271,21 +274,22 @@ public class OAuthController {
 
 	// 토큰 발급하는 부분
 	@RequestMapping(value = "/token", method = RequestMethod.POST, produces = "application/json")
-	public @ResponseBody Token Token(@RequestParam(value = "grant_type", required = true) String grantType,
+	public @ResponseBody String Token(@RequestParam(value = "grant_type", required = true) String grantType,
 			@RequestParam(value = "code", required = false) String code,
 			@RequestParam(value = "refresh_token", required = false) String refreshToken, HttpSession httpSession,
-			@RequestHeader HttpHeaders headers)
+			@RequestHeader HttpHeaders headers, HttpServletResponse response)
 			throws NoSuchAlgorithmException, UnsupportedEncodingException, GeneralSecurityException {
 
+		response.setStatus(HttpServletResponse.SC_OK);
 		logger.info("[STEP #5] /api/oauth2/token");
 		// TODO Code유효성 검사
 		// TODO token 발급
-		logger.info(code);
-		logger.info(grantType);
+		logger.info("grant_type: " + grantType);
 		ValueOperations<String, Object> vop = redisTemplate.opsForValue();
 
 		String newAccessToken = ""; // 생성해야 함.
 		String newRefreshToken = ""; // 생성해야 함.
+		String answer = null; // 단지서버에 토큰 관련요청 후 수신하는 응답
 		Token token = new Token();
 		if (grantType.equals("authorization_code")) {
 			// TODO 코드 검사
@@ -314,9 +318,8 @@ public class OAuthController {
 				String clientId = JWTUtils.getClientInfoFromToken(newAccessToken);
 				ClientInfo clientInfo = clientInfoRepo.findByClientId(clientId);
 				String url = clientInfo.getEndPoint();
-				if (!DanziAuthUtils.create(token, url)) {
-					throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
-				}
+
+				answer = DanziAuthUtils.create(token, url);
 
 			}
 		} else if (grantType.equals("refresh_token")) {
@@ -329,38 +332,80 @@ public class OAuthController {
 				if (headers.get("Authorization").get(0) == null)
 					throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, ERROR.INVALID_CLIENT);
 
-				if (!validateHeaderAuth(headers.get("Authorization").get(0)))
-					throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, ERROR.INVALID_CLIENT);
+//				if (!validateHeaderAuth(headers.get("Authorization").get(0)))
+//					throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, ERROR.INVALID_CLIENT);
 
 				// 단지에 갱신토큰 유효성 확인
 				String clientId = JWTUtils.getClientInfoFromToken(refreshToken);
 				ClientInfo clientInfo = clientInfoRepo.findByClientId(clientId);
 				String url = clientInfo.getEndPoint();
+				String isValidToken = DanziAuthUtils.get(url, refreshToken);
+				logger.info(isValidToken);
+				JSONObject isValidTokenJson = new JSONObject(isValidToken);
+				logger.info(isValidTokenJson.toString());
+				
+				if (!isValidTokenJson.get("result").toString().equalsIgnoreCase("success")) {
+					
+					if (isValidTokenJson.getJSONObject("error").getInt("code") == -200) //서버에러인경우 
+						throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
+					
+					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+					logger.info(isValidTokenJson.get("result").toString());
+					JSONObject error = new JSONObject();
+					error.put("error", "invalid_grant");
+					error.put("error_description", "invalid token");
+					return error.toString();
+				}
 
-				if (!DanziAuthUtils.get(url, refreshToken))
-					throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR); // 에러를 invalid ? internal?
-
+				// 유효한 토큰인 경우 토큰 생성
 				JWTInfo jwtinfo = JWTUtils.getJWTInfoFromToken(refreshToken);
 				newAccessToken = JWTUtils.generateToken(jwtinfo, "accessToken");
 				newRefreshToken = JWTUtils.generateToken(jwtinfo, "refreshToken");
 				token.setAccess_token(newAccessToken);
 				token.setRefresh_token(newRefreshToken);
 
-				if (!DanziAuthUtils.refresh(url, token, refreshToken))
-					throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
+				// 단지서버에 갱신된 토큰 전달
+				answer = DanziAuthUtils.refresh(url, token, refreshToken);
+				logger.info(answer);
 
 			}
 		} else {
 			throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
 		}
 
+		// 갱신된 토큰 전달에 대한 응답처리
+		logger.info(answer);
+		if (answer == null) {
+			throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
+		} else {
+			JSONObject obj = new JSONObject(answer);
+			logger.info(obj.get("result").toString());
+			if (!obj.get("result").toString().equalsIgnoreCase("success")) {
+				
+				if (obj.getJSONObject("error").getInt("code") == -200) //서버에러인경우 
+					throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
+				
+				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+				JSONObject error = new JSONObject();
+				error.put("error", "invalid_grant");
+				error.put("error_description", "invalid token");
+				return error.toString();
+			}
+		}
+
 		// class 만들어서 사용하는 것으로 변경해야함.
 		logger.info(token.toString());
 
 		// TODO 단지서버로 전송하고 정상 응답 받은 경우에만 정상리턴 -> 아닌경우에는 500
 		// 토큰 생성인 경우와 갱신인 경우 구분해서 처리 create, refresh
 
-		return token;
+		JSONObject tokenResult = new JSONObject();
+		tokenResult.put("access_token", token.getAccess_token());
+		tokenResult.put("refresh_token", token.getRefresh_token());
+		tokenResult.put("token_type", token.getToken_type());
+		tokenResult.put("expires_in", token.getExpires_in());
+
+		return tokenResult.toString();
 
 	}
 
@@ -376,7 +421,7 @@ public class OAuthController {
 			return false;
 
 		// Base64 디코드
-		String decodeStr = new String(Base64.getDecoder().decode(splitStr[1]));
+		String decodeStr = new String(Base64.getDecoder().decode(splitStr[1].trim()));
 
 		splitStr = decodeStr.split(":");
 		// splitStr length 가 2가 아니면 유효하지 않은 authorization 값

+ 14 - 24
java/com/icontrols/oauth/utils/DanziAuthUtils.java

@@ -25,7 +25,7 @@ public class DanziAuthUtils {
 	@Autowired
 	ClientInfoRepository clientInfoRepo;
 
-	public static boolean create(Token newToken, String url)
+	public static String create(Token newToken, String url)
 			throws UnsupportedEncodingException, NoSuchAlgorithmException, GeneralSecurityException {
 
 		Map<String, Object> body = new HashMap<>();
@@ -52,19 +52,19 @@ public class DanziAuthUtils {
 		try {
 			answer = template.postForObject(endpoint, entity, String.class);
 		} catch (Exception e) {
-			return false;
+			return null;
 		}
 
-		logger.info(answer);
-		JSONObject obj = new JSONObject(answer);
-		if (!obj.get("result").toString().equalsIgnoreCase("success")) {
-			return false;
-		}
+//		logger.info(answer);
+//		JSONObject obj = new JSONObject(answer);
+//		if (!obj.get("result").toString().equalsIgnoreCase("success")) {
+//			return false;
+//		}
 
-		return true;
+		return answer;
 	}
 
-	public static boolean refresh(String url, Token newToken, String prevToken) {
+	public static String refresh(String url, Token newToken, String prevToken) {
 
 		Map<String, Object> body = new HashMap<>();
 		Map<String, Object> token = new HashMap<>();
@@ -88,19 +88,13 @@ public class DanziAuthUtils {
 		try {
 			answer = template.postForObject(endpoint, entity, String.class);
 		} catch (Exception e) {
-			return false;
-		}
-
-		logger.info(answer);
-		JSONObject obj = new JSONObject(answer);
-		if (!obj.get("result").toString().equalsIgnoreCase("success")) {
-			return false;
+			return null;
 		}
 
-		return true;
+		return answer;
 	}
 
-	public static boolean get(String url, String refreshToken) {
+	public static String get(String url, String refreshToken) {
 
 		Map<String, Object> body = new HashMap<>();
 		Map<String, Object> token = new HashMap<>();
@@ -122,16 +116,12 @@ public class DanziAuthUtils {
 		try {
 			answer = template.postForObject(endpoint, entity, String.class);
 		} catch (Exception e) {
-			return false;
+			return null;
 		}
 
 		logger.info(answer);
-		JSONObject obj = new JSONObject(answer);
-		if (!obj.get("result").toString().equalsIgnoreCase("success")) {
-			return false;
-		}
 
-		return true;
+		return answer;
 	}
 
 }

+ 6 - 6
java/com/icontrols/oauth/utils/JWTUtils.java

@@ -58,20 +58,20 @@ public class JWTUtils {
 		} else if (type.equals("refreshToken")) {
 			secretKey = CONSTANTS.REFRESH_TOKEN_SECRET_KEY;
 		}
-		logger.info(token);
+		logger.info("origin = " + token);
 
 		if (token.split("\\.")[0] == null || token.split("\\.")[1] == null || token.split("\\.")[2] == null)
 			return false;
 
 		Decoder decoder = Base64.getDecoder();
 		// 시그니처가 맞는지 확인
-		String enHeader = token.split("\\.")[0];
-		logger.info("H= " + enHeader);
+//		String enHeader = token.split("\\.")[0];
+//		logger.info("H= " + enHeader);
 		String enPayload = token.split("\\.")[1];
 		String dePayload = new String(decoder.decode(enPayload));
-		logger.info("P= " + enPayload);
-		String signiture = token.split("\\.")[2];
-		logger.info("S= " + signiture);
+//		logger.info("P= " + enPayload);
+//		String signiture = token.split("\\.")[2];
+//		logger.info("S= " + signiture);
 		JSONObject obj = new JSONObject(dePayload);
 
 		if (obj.isNull("cmpIp") || obj.isNull("homeId") || obj.isNull("iat") || obj.isNull("clientInfo"))

+ 2 - 1
src/main/webapp/WEB-INF/jsp/InsertCode.jsp

@@ -119,7 +119,8 @@ img {
 							console.log(data);
 							if (data == true) {
 								//window.location.href = 'http://127.0.0.1:8003/api/oauth2/code/generate';
-								window.location.href = 'https://teldev.hdc-smart.com:443/api/oauth2/code/generate';
+								//window.location.href = 'https://telproxy.hdc-smart.com/api/oauth2/code/generate';
+								window.location.href = 'https://teldev.hdc-smart.com/api/oauth2/code/generate';
 							} else {
 								alert("인증 실패");
 							}