반응형
카카오 API를 통해서 카카오 로그인을 남겨보려고 해요
https://developers.kakao.com/먼저 로그인을 하시고 내 애플리케이션 가서 만드시면 화면처럼 키가 발급이 되었을 거예요
저는 카카오 Rest Api를 사용해서 로그인을 할 거예요Rest방식은 Spring RestTemplate를 이용해서 가져올 거예요
카카오 인증절차예요.
카카오개발자(https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api) 사이트에서 가져왔어요
먼저 https://kauth.kakao.com/oauth/authorize?client_id={apiKey}&redirect_uri={returnUrl}&response_type=code
restApi키와 등록한 returnUrl을 넘기면
정상적으로 호출이 되면 동의 화면이 나올 거예요 황목설정은 "동의 항목"에서 설정이 가능해요
이제 "동의하고 계속하기"클릭 시 설정한 returnUrl로 redirect가 되면서 code이 넘어와요.
private static final String kakaoReturnUrl = "returnUrl";
private static final String kakaoLoginUrl = "https://kauth.kakao.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code";
private static final String kakaoKey = "apiKey";
private static final String kakaoToken = "https://kauth.kakao.com/oauth/token";
private static final String kakaoProfile = "https://kapi.kakao.com/v2/user/me";
private OverlapLogin loginManager = OverlapLogin.getInstance();
@RequestMapping(value ="/openId/kakao", method=RequestMethod.GET)
public String kakaoLogin(HttpServletRequest request, Model model, HttpSession session ) {
return "redirect:" + String.format(kakaoLoginUrl, kakaoKey, (getServerName(request, kakaoReturnUrl)));
}
@RequestMapping(value ="/openId/kakaoLogin")
public String kakaoLoginCallback(EnnacoreMap enna, Model model, HttpSession session,HttpServletRequest request, HttpServletResponse response ) throws Exception {
//로그인 후 받는 code값
String code = request.getParameter("code");
MultiValueMap<String, Object> mmap = new LinkedMultiValueMap<String, Object>();
mmap.add("grant_type", "authorization_code"); //필수 고정값
mmap.add("client_id", kakaoKey); //카카오 rest_key
mmap.add("redirect_url", getServerName(request, kakaoReturnUrl)); //응답받은 리턴URL
mmap.add("code", code); //카카오 로그인 후
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=utf-8"); //헤더지정
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String,Object>>(mmap, headers);
RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter converter = new FormHttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_FORM_URLENCODED));
restTemplate.getMessageConverters().add(converter);
//code를 이용해 로그인 사용자 token값 가벼오기
ResponseEntity<AccessTokenRequestResponse> tokenResponse = restTemplate.postForEntity(kakaoToken, httpEntity, AccessTokenRequestResponse.class);
headers.add("Authorization", "Bearer " + tokenResponse.getBody().getAccess_token());
mmap.clear();
httpEntity = new HttpEntity<MultiValueMap<String,Object>>(mmap, headers);
//해당 토큰값으로 사용자 정보 가져오기
ResponseEntity<UserProfileViewResponse> profileResponse = restTemplate.postForEntity(kakaoProfile, httpEntity, UserProfileViewResponse.class);
// logger.info("loginRecd::::"+profileResponse.getBody().getKakao_account().getAge_range());
// logger.info("loginRecd::::"+profileResponse.getBody().getKakao_account().getBirthday());
// logger.info("loginRecd::::"+profileResponse.getBody().getKakao_account().getEmail());
// logger.info("loginRecd::::"+profileResponse.getBody().getProperties().getNickname());
}
public String getServerName(HttpServletRequest req, String returnUrl) {
StringBuffer serverName = new StringBuffer("");
serverName.append("http://");
serverName.append(req.getServerName());
serverName.append(returnUrl);
return serverName.toString();
}
VO class들은 파일로 올렸습니다
반응형
'개발 > Java' 카테고리의 다른 글
egov 3.9버전 mybatis association 사용시 에러(org.apache.ibatis.javassist.util.proxy.SecurityActions.setAccessible) (0) | 2020.11.19 |
---|---|
Java Jpa Specifications사용하기 (0) | 2020.09.23 |
ksoap2이용하여 SOAP API가져오기 (0) | 2020.09.14 |
Java Custom Annotation (0) | 2020.08.19 |
JAVA Spring Validation (0) | 2020.08.19 |