OAuth ( Open Auth ) : 로그인 인증처리를 대신해준다.

                                   인증처리, 권한부여

 

※ 원래는 카카오DB에 홍길동 정보에 접근할수 있는건, 홍길동뿐임. 그러나 Oauth 를 통하여 접근권한을 위임함.

 

 

 

스프링 공식 OAuth 주체 (OAuth-Client): Facebook, google

 

 

 

 

https://developers.kakao.com/  

로그인 후,

 

 

로컬에서 테스트용이기에 적당학 임의작성

 

 

 

웹에서 사용할것이기에 REST API키 사용 예정

 

 

 

 

 

로그인 성공시 콜백받을 주소,

 

 

카카오로 로그인 메뉴에서 활성화 설정

 

 

 

 

간단테스를 위해 동의항목메뉴에서, 닉네임만 설정함

 

동작원리

 

웹 jsp에 등록할 링크 ( get방식 )

 

메모장에 적어놓고 구분해보았다. 링크를 사용할땐 쭉이어서 달아주면된다.

 

컨트롤러 카카오 인가code받기

 

 

발급받은 인가 코드를 통하여 사용자토큰을 받으면 , 홍길동이 동의해준 정보에 접근할수 있다.

 


 

사용자 토큰받기 ( post방식 - http body에 데이터를 전)

 

 

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

@Controller
public class MemberController {
	
	@RequestMapping("/index")
	public String test() {
	return "index";
	}
	
	@RequestMapping(value = "/kakaoLog", method = RequestMethod.GET)
	@ResponseBody
	public String kakaoCallback(String code){

//		Https://kauth.kakao.com/oauth/token 
//			grant_type = authorization_code
//			client_id = REST API키
//			redirect_uri = 설정한 redirect_uri
//			code = 인가 코드 받기 요청으로 얻은 인가 코드
//			client_secret = 필수x
		
		
		
		// HttpHeader 오브젝트 생성
		RestTemplate rt = new RestTemplate(); 
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-type","application/x-www-form-urlencoded;charset=utf-8");
		
		//HttpBody 오브젝트 생성
		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		params.add("grant_type", "authorization_code");
		params.add("client_id", "REST API키");
		params.add("redirect_uri", "http://localhost:8088/pro/kakaoLog");
		params.add("code", code);
		
		
		// HttpHeader + HttpBody 를 하나의 오브젝트에 담기
		HttpEntity<MultiValueMap<String,String>> kakaoTokenRequest = 
				new HttpEntity<>(params,headers);
		
		
		//왜 HttpEntity 에 하나로 담느냐 ????
		//RestTemplate의 exchange 메서드가     HttpEntity를 받도록 되어져있다.
		
		
		
		//실제 요청 ( Http요청하기 - post방식으로, response 변수 응답받음 )
		ResponseEntity<String> response = rt.exchange(
			"Https://kauth.kakao.com/oauth/token", //토큰발급요청주소
			HttpMethod.POST, 						// 요청방식
			kakaoTokenRequest,						//데이터 (바디와 헤더값)
			String.class 							// 응답받을 타입
		);
		
		
		return "카카오인증 후, 사용자 토큰요청에 대한 응답 : " + response;
	}

웹결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

참고 https://www.youtube.com/watch?v=NwQ_55l0Za4

+ Recent posts