문의 시, 사용하시는 개발환경과 디벨로퍼스 앱ID를 알려주세요.
개발환경: java spring mvc
앱 ID 1046257
package org.zerock.controller;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.zerock.domain.AuthVo;
import org.zerock.domain.MemberVo;
import org.zerock.security.domain.CustomUser;
import org.zerock.service.KakaoService;
import org.zerock.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
@Controller
@Log4j
@AllArgsConstructor
public class KakaoController {
private KakaoService kakaoService;
private UserService userService;
@RequestMapping(value="/kakao/callback", method = RequestMethod.GET)
public String redirectKakao(@RequestParam("code") String code, HttpSession session) throws IOException{
log.info("code::" +code);
// 접속토큰 get
String kakaoToken = kakaoService.getReturnAccessToken(code);
log.info("kakaoToken :: " + kakaoToken);
// 접속자 정보 get
Map<String, Object> result = kakaoService.getUserInfo(kakaoToken);
log.info("result : " + result);
String snsId = (String)result.get("id");
String userName = (String)result.get("nickname");
String email = (String)result.get("email");
String userpw = snsId;
log.info(snsId);
// 분기
MemberVo memberVo = new MemberVo();
// 일치하는 snsId 없을 시 회원가입
if(userService.kakapLogin(snsId) == null) {
log.warn("카카오로 회원가입");
memberVo.setUserid(email);
memberVo.setUserpw(userpw);
memberVo.setUserName(userName);
memberVo.setSnsId(snsId);
memberVo.setUserEmail(email);
userService.kakaoJoin(memberVo);
AuthVo auth = new AuthVo();
auth.setUserid(email);
auth.setAuth("ROLE_USER");
userService.insertRole(auth);
}
// 일치하는 snsId가 있으면 멤버객체에 담음
log.warn("카카오로 로그인");
String userid = userService.findUserIdBySnsId(snsId);
MemberVo vo = userService.getUserById(userid);
log.warn("member : " +vo);
CustomUser user = new CustomUser(vo);
log.warn("user : " + user);
List<GrantedAuthority> roles = user.getList(vo);
Authentication auth = new UsernamePasswordAuthenticationToken(user, null, roles);
log.warn("auth : " + auth);
SecurityContextHolder.getContext().setAuthentication(auth);
// 로그아웃 처리시 사용할 토큰 값
session.setAttribute("kakaoToken", kakaoToken);
return "redirect:/";
}
}
컨트롤러 입니다
package org.zerock.service;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.log4j.Log4j;
@Service
@Log4j
public class KakaoService {
public String getReturnAccessToken(String code) {
String access_token = “”;
String refresh_token = “”;
String reqURL = “https://kauth.kakao.com/oauth/token”;
try {
URL url = new URL(reqURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//HttpURLConnection 설정 값 셋팅
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// buffer 스트림 객체 값 셋팅 후 요청
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
StringBuilder sb = new StringBuilder();
sb.append("grant_type=authorization_code");
sb.append("&client_id=9187c7f33336133c6a2a5c937307eafc"); //앱 KEY VALUE
sb.append("&redirect_uri=http://localhost:8080/kakao/callback"); // 앱 CALLBACK 경로
sb.append("&code=" + code);
bw.write(sb.toString());
bw.flush();
int responseCode = conn.getResponseCode();
log.info("responseCode : " + responseCode);
// RETURN 값 result 변수에 저장
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String br_line = "";
String result = "";
log.info("response body : " + result);
while ((br_line = br.readLine()) != null) {
result += br_line;
}
//Gson 라이브러리에 포함된 클래스로 JSON파싱 객체 생성
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result);
// 토큰 값 저장 및 리턴
access_token = element.getAsJsonObject().get("access_token").getAsString();
refresh_token = element.getAsJsonObject().get("refresh_token").getAsString();
log.info("access_token : " + access_token);
log.info("refresh_token : " + refresh_token);
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
return access_token;
}
public Map<String,Object> getUserInfo(String access_token) {
Map<String,Object> resultMap =new HashMap<>();
String reqURL = "https://kapi.kakao.com/v2/user/me";
try {
URL url = new URL(reqURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//요청에 필요한 Header에 포함될 내용
conn.setRequestProperty("Authorization", "Bearer " + access_token);
int responseCode = conn.getResponseCode();
System.out.println("responseCode : " + responseCode);
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String br_line = "";
String result = "";
while ((br_line = br.readLine()) != null) {
result += br_line;
}
System.out.println("response:" + result);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result);
log.warn("element:: " + element);
JsonObject properties = element.getAsJsonObject().get("properties").getAsJsonObject();
JsonObject kakao_account = element.getAsJsonObject().get("kakao_account").getAsJsonObject();
log.warn("id:: "+element.getAsJsonObject().get("id").getAsString());
String id = element.getAsJsonObject().get("id").getAsString();
String nickname = properties.getAsJsonObject().get("nickname").getAsString();
String email = kakao_account.getAsJsonObject().get("email").getAsString();
log.warn("email:: " + email);
resultMap.put("nickname", nickname);
resultMap.put("id", id);
resultMap.put("email", email);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultMap;
}
}
서비스 입니다
카카오 로그인 기능 구현중 Server returned HTTP response code: 401 for URL: https://kapi.kakao.com/v2/user/me 에러가 뜨는데 어느곳을 손봐야할지 모르겠습니다