SNS 연동 로그인 처리 DB화 변경작업 - 중간백업
This commit is contained in:
parent
803e8e98b1
commit
939c6d459b
@ -13,6 +13,8 @@ import com.github.scribejava.core.model.Response;
|
||||
import com.github.scribejava.core.model.Verb;
|
||||
import com.github.scribejava.core.oauth.OAuth20Service;
|
||||
|
||||
import nlib.util.StringUtil;
|
||||
|
||||
|
||||
public class OAuthLogin {
|
||||
private OAuth20Service oauthService;
|
||||
@ -74,10 +76,30 @@ public class OAuthLogin {
|
||||
} else if (this.oauthVO.isNaver()) {
|
||||
user.setServiceName(OAuthConfig.NAVER_SERVICE_NAME);
|
||||
JsonNode resNode = rootNode.get("response");
|
||||
user.setUserId(resNode.get("id").asText());
|
||||
user.setNickName(resNode.get("nickname").asText());
|
||||
|
||||
// 사용자 내부 고유 ID (예: kh3lhfSg2v7TnJLmdhH7a0HyL-1zExIS4cF1mD4Hi4Y)
|
||||
user.setUid(resNode.get("id").asText());
|
||||
|
||||
// 사용자로그인ID (메일형식)
|
||||
user.setUserId(resNode.get("email").asText());
|
||||
|
||||
// 사용자명 (예: 홍길동)
|
||||
user.setUserName(resNode.get("name").asText());
|
||||
|
||||
// 메일주소
|
||||
user.setEmail(resNode.get("email").asText());
|
||||
|
||||
// 생년월일
|
||||
String birthday = StringUtil.getString(resNode.get("birthday").asText(), "0000");
|
||||
String birthyear = StringUtil.getString(resNode.get("birthyear").asText(), "0000");
|
||||
birthday = birthday.replaceAll("-", "");
|
||||
if(birthday.length() != 4) birthday = "0000";
|
||||
if(birthyear.length() != 4) birthyear = "0000";
|
||||
user.setBirthdate(birthyear + birthday);
|
||||
|
||||
// 성별
|
||||
user.setGender(resNode.get("gender").asText());
|
||||
|
||||
} else if (this.oauthVO.isKakao()) {
|
||||
user.setServiceName(OAuthConfig.KAKAO_SERVICE_NAME);
|
||||
JsonNode resNode = rootNode.get("properties");
|
||||
|
||||
@ -2,7 +2,29 @@ package egovframework.com.ext.oauth.service;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import nlib.util.StringUtil;
|
||||
|
||||
public class OAuthUniversalUser {
|
||||
|
||||
private String uid;
|
||||
|
||||
private String email;
|
||||
private String userId;
|
||||
private String userName;
|
||||
private String nickName;
|
||||
|
||||
private String birthdate;
|
||||
private String gender;
|
||||
|
||||
private String serviceName;
|
||||
|
||||
private String loginIp;
|
||||
private Date lastLogin;
|
||||
|
||||
public boolean isValid() {
|
||||
return StringUtil.isNotEmpty(uid) && StringUtil.isNotEmpty(userId);
|
||||
}
|
||||
|
||||
public String getUid() {
|
||||
return uid;
|
||||
}
|
||||
@ -67,16 +89,36 @@ public class OAuthUniversalUser {
|
||||
this.lastLogin = lastLogin;
|
||||
}
|
||||
|
||||
private String uid;
|
||||
|
||||
private String email;
|
||||
private String userId;
|
||||
private String userName;
|
||||
private String nickName;
|
||||
|
||||
private String serviceName;
|
||||
|
||||
private String loginIp;
|
||||
private Date lastLogin;
|
||||
|
||||
public String getBirthdate() {
|
||||
return birthdate;
|
||||
}
|
||||
|
||||
public void setBirthdate(String birthdate) {
|
||||
this.birthdate = birthdate;
|
||||
}
|
||||
|
||||
public String getLoginIp() {
|
||||
return loginIp;
|
||||
}
|
||||
|
||||
public void setLoginIp(String loginIp) {
|
||||
this.loginIp = loginIp;
|
||||
}
|
||||
|
||||
public Date getLastLogin() {
|
||||
return lastLogin;
|
||||
}
|
||||
|
||||
public void setLastLogin(Date lastLogin) {
|
||||
this.lastLogin = lastLogin;
|
||||
}
|
||||
|
||||
public String getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
public void setGender(String gender) {
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -102,17 +102,26 @@ public class NlibCommonController {
|
||||
userId = ((NlibLoginVO)authentication.getPrincipal()).getUserId();
|
||||
}
|
||||
|
||||
if(nlib.util.StringUtil.isEmpty(userId)) {
|
||||
authKey = ANONYMOUS_AUTH_KEY_PREFIX + request.getSession().getId();
|
||||
} else {
|
||||
authKey = Base64.getEncoder().encodeToString(userId.getBytes());
|
||||
}
|
||||
authKey = makeAuthKey(userId, request.getSession().getId());
|
||||
|
||||
log.debug("createAuthKey > " + authKey);
|
||||
|
||||
return authKey;
|
||||
}
|
||||
|
||||
public static String makeAuthKey(String userId) {
|
||||
return makeAuthKey(userId, null);
|
||||
}
|
||||
public static String makeAuthKey(String userId, String sessionId) {
|
||||
|
||||
if(nlib.util.StringUtil.isEmpty(userId)) {
|
||||
if(nlib.util.StringUtil.isNotEmpty(sessionId)) return ANONYMOUS_AUTH_KEY_PREFIX + sessionId;
|
||||
else return null;
|
||||
}
|
||||
|
||||
return Base64.getEncoder().encodeToString(userId.getBytes());
|
||||
}
|
||||
|
||||
public ResponseEntity<String> makeResponseEntityJson(DataApiResVO resVO) {
|
||||
|
||||
// Convert Json
|
||||
|
||||
@ -7,7 +7,7 @@ import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import nlib.user.service.UserInfoVO;
|
||||
import nlib.user.service.NlibLoginVO;
|
||||
|
||||
/**
|
||||
* <pre>
|
||||
@ -31,7 +31,7 @@ import nlib.user.service.UserInfoVO;
|
||||
* @version 1.0
|
||||
*
|
||||
*/
|
||||
public class SecUserVO extends UserInfoVO implements UserDetails {
|
||||
public class SecUserVO extends NlibLoginVO implements UserDetails {
|
||||
|
||||
private static final long serialVersionUID = -8274004534207618048L;
|
||||
|
||||
|
||||
@ -9,6 +9,8 @@ import nlib.restful.service.DataApiResVO;
|
||||
public interface LoginService
|
||||
{
|
||||
public String login(HttpServletRequest req, String username, String password);
|
||||
|
||||
public String loginOauth(String snsUid);
|
||||
|
||||
public DataApiResVO logout(DataApiReqVO reqVO);
|
||||
|
||||
|
||||
@ -20,6 +20,7 @@ import nlib.restful.service.DataApiReqVO;
|
||||
import nlib.restful.service.DataApiResVO;
|
||||
import nlib.security.SecUserVO;
|
||||
import nlib.user.service.LoginService;
|
||||
import nlib.util.StringUtil;
|
||||
|
||||
@Service("loginService")
|
||||
public class LoginServiceImpl implements LoginService
|
||||
@ -70,6 +71,45 @@ public class LoginServiceImpl implements LoginService
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* SNS 연동을 통한 로그인 처리를 수행한다.
|
||||
*
|
||||
*/
|
||||
public String loginOauth(String snsUid) {
|
||||
|
||||
// SNS 연동 사용자UID로 사용자정보 조회
|
||||
if(StringUtil.isEmpty(snsUid)) return null;
|
||||
|
||||
// // 아이디와 패스워드로, Security 가 알아 볼 수 있는 token 객체로 변경한다.
|
||||
// UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
|
||||
//
|
||||
// try {
|
||||
// // AuthenticationManager 에 token 을 넘기면 UserDetailsService 가 받아 처리하도록 한다.
|
||||
// Authentication authentication = authenticationManager.authenticate(token);
|
||||
//
|
||||
// // AuthKey 등록
|
||||
// SecUserVO userVO = (SecUserVO)authentication.getPrincipal();
|
||||
// userVO.setAuthKey(req.getSession().getId()); // TODO : 임시로 세션ID 넣음, 실제 Authkey 생성 규칙에 따른 해당 키 설정 처리 필요
|
||||
//
|
||||
// // 실제 SecurityContext 에 authentication 정보를 등록한다.
|
||||
// SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
//
|
||||
// // TODO : 로그인 로그 정보를 통합자료시스템에 전송한다.
|
||||
//
|
||||
// } catch (DisabledException e) {
|
||||
// return "/login/loginForm.do?error=locked";
|
||||
// } catch (LockedException e) {
|
||||
// return "/login/loginForm.do?error=disable";
|
||||
// } catch (BadCredentialsException e) {
|
||||
// return "/login/loginForm.do?error=invalid-password";
|
||||
// } catch (Exception e) {
|
||||
// return "/login/loginForm.do?error=other." + e.toString();
|
||||
// }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public DataApiResVO logout(DataApiReqVO reqVO) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -6,10 +6,12 @@ import java.net.URI;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.inject.Inject;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
@ -28,6 +30,7 @@ import org.springframework.ui.Model;
|
||||
import org.springframework.ui.ModelMap;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
@ -42,6 +45,10 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
|
||||
import com.github.scribejava.core.model.OAuth2AccessToken;
|
||||
|
||||
import egovframework.com.ext.oauth.service.OAuthConfig;
|
||||
import egovframework.com.ext.oauth.service.OAuthLogin;
|
||||
import egovframework.com.ext.oauth.service.OAuthUniversalUser;
|
||||
import egovframework.com.ext.oauth.service.OAuthVO;
|
||||
import nlib.cmm.snslogin.GoogleOAuthResponse;
|
||||
import nlib.cmm.snslogin.KakaoController;
|
||||
import nlib.cmm.snslogin.NaverLoginBO;
|
||||
@ -59,8 +66,10 @@ import nlib.util.StringUtil;
|
||||
*
|
||||
* </pre>
|
||||
*
|
||||
* @ ------------ -------- --------------------------- @ 수정일 수정자 수정내용 @
|
||||
* ------------ -------- --------------------------- @ 2021. 7. 9. KNKIM 최초 생성
|
||||
* @ ------------ -------- ---------------------------
|
||||
* @ 수정일 수정자 수정내용
|
||||
* @ ------------ -------- ---------------------------
|
||||
* @ 2021. 7. 9. KNKIM 최초 생성
|
||||
*
|
||||
*
|
||||
* @author 이씨플라자 * DIGITALSHIP KNKIM
|
||||
@ -70,16 +79,31 @@ import nlib.util.StringUtil;
|
||||
*/
|
||||
@Controller
|
||||
public class LoginController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(LoginController.class);
|
||||
|
||||
//-------------------------------------------
|
||||
// SNS 연동
|
||||
//-------------------------------------------
|
||||
@Inject
|
||||
private OAuthVO naverAuthVO;
|
||||
|
||||
@Inject
|
||||
private OAuthVO googleAuthVO;
|
||||
|
||||
/* NaverLoginBO */
|
||||
private NaverLoginBO naverLoginBO;
|
||||
private String apiResult = null;
|
||||
@Inject
|
||||
private OAuthVO kakaoAuthVO;
|
||||
//-------------------------------------------
|
||||
|
||||
|
||||
@Autowired
|
||||
private void setNaverLoginBO(NaverLoginBO naverLoginBO) {
|
||||
this.naverLoginBO = naverLoginBO;
|
||||
}
|
||||
// /* NaverLoginBO */
|
||||
// private NaverLoginBO naverLoginBO;
|
||||
// private String apiResult = null;
|
||||
|
||||
// @Autowired
|
||||
// private void setNaverLoginBO(NaverLoginBO naverLoginBO) {
|
||||
// this.naverLoginBO = naverLoginBO;
|
||||
// }
|
||||
|
||||
@Resource(name = "loginService")
|
||||
private LoginService loginService;
|
||||
@ -103,130 +127,204 @@ public class LoginController {
|
||||
if (logout != null) {
|
||||
model.addAttribute("logout", String.format("로그아웃하였습니다 %s", logout));
|
||||
}
|
||||
// 네이버 로그인 URL 생성
|
||||
/* 네이버아이디로 인증 URL을 생성하기 위하여 naverLoginBO클래스의 getAuthorizationUrl메소드 호출 */
|
||||
naverLoginBO.setRedirect_url("http://nlib.nculture.org/nlib/login/naverCallback.do");
|
||||
String naverAuthUrl = naverLoginBO.getAuthorizationUrl(session);
|
||||
|
||||
// 구글 로그인 URL 생성
|
||||
String googleUrl = "https://accounts.google.com/o/oauth2/v2/auth?"
|
||||
+ "client_id=879126511006-jro7bld7b2epl3n5mkksp0p24k2inbpu.apps.googleusercontent.com"
|
||||
+ "&redirect_uri=http://nlib.nculture.org/nlib/login/googleCallback.do"
|
||||
+ "&response_type=code"
|
||||
+ "&scope=email%20profile%20openid"
|
||||
+ "&access_type=offline";
|
||||
// SNS 연동 URL 생성
|
||||
OAuthLogin naverLogin = new OAuthLogin(naverAuthVO);
|
||||
log.debug("naverLogin.getOAuthURL() = "+naverLogin.getOAuthURL());
|
||||
model.addAttribute("naverUrl", naverLogin.getOAuthURL());
|
||||
|
||||
// 카카오 로그인 URL 생성
|
||||
String k_redirect_url="http://nlib.nculture.org/nlib/login/kakaoCallback.do";
|
||||
String kakaoUrl = KakaoController.getAuthorizationUrl(session,k_redirect_url);
|
||||
OAuthLogin googleLogin = new OAuthLogin(googleAuthVO);
|
||||
log.debug("googleLogin.getOAuthURL() = "+googleLogin.getOAuthURL());
|
||||
model.addAttribute("googleUrl", googleLogin.getOAuthURL());
|
||||
|
||||
model.addAttribute("naverUrl", naverAuthUrl);
|
||||
model.addAttribute("googleUrl", googleUrl);
|
||||
model.addAttribute("kakaoUrl", kakaoUrl);
|
||||
OAuthLogin kakaoLogin = new OAuthLogin(kakaoAuthVO);
|
||||
log.debug("kakaoLogin.getOAuthURL() = "+kakaoLogin.getOAuthURL());
|
||||
model.addAttribute("kakaoUrl", kakaoLogin.getOAuthURL());
|
||||
|
||||
return "nlib/login/loginForm";
|
||||
}
|
||||
|
||||
// 네이버 로그인 성공시 callback호출 메소드
|
||||
@RequestMapping(value = "/login/naverCallback.do", method = { RequestMethod.GET, RequestMethod.POST })
|
||||
public String naverCallback(Model model, @RequestParam String code, @RequestParam String state, HttpSession session)
|
||||
throws IOException, ParseException {
|
||||
OAuth2AccessToken oauthToken;
|
||||
oauthToken = naverLoginBO.getAccessToken(session, code, state);
|
||||
// 로그인 사용자 정보를 읽어온다.
|
||||
apiResult = naverLoginBO.getUserProfile(oauthToken);
|
||||
JSONParser parser = new JSONParser();
|
||||
Object obj = parser.parse(apiResult);
|
||||
JSONObject jsonObj = (JSONObject) obj;
|
||||
JSONObject response_obj = (JSONObject) jsonObj.get("response");
|
||||
String email = (String) response_obj.get("email");
|
||||
model.addAttribute("result", apiResult);
|
||||
|
||||
/* 네이버 로그인 성공 페이지 View 호출 */
|
||||
return "naverSuccess";
|
||||
}
|
||||
|
||||
// 구글 로그인 콜백
|
||||
@RequestMapping(value = "/login/googleCallback.do")
|
||||
public String googleCallback(@RequestParam(value = "code") String authCode, HttpSession session, Model model,
|
||||
HttpServletRequest request) throws Exception {
|
||||
|
||||
String code = request.getParameter("code");
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
|
||||
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
|
||||
parameters.add("code", code);
|
||||
parameters.add("client_id", "879126511006-jro7bld7b2epl3n5mkksp0p24k2inbpu.apps.googleusercontent.com");
|
||||
parameters.add("client_secret", "F6T-ZV9jibLhKtcugxPUtBlN");
|
||||
parameters.add("redirect_uri", "http://nlib.nculture.org/nlib/login/googleCallback.do");
|
||||
parameters.add("grant_type", "authorization_code");
|
||||
|
||||
HttpEntity<MultiValueMap<String,String>> rest_request = new HttpEntity<>(parameters,headers);
|
||||
|
||||
URI uri = URI.create("https://www.googleapis.com/oauth2/v4/token");
|
||||
|
||||
ResponseEntity<String> resultEntity;
|
||||
resultEntity = restTemplate.postForEntity(uri, rest_request, String.class);
|
||||
// JSON 파싱을 위한 기본값 세팅
|
||||
// 요청시 파라미터는 스네이크 케이스로 세팅되므로 Object mapper에 미리 설정해준다.
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
|
||||
mapper.setSerializationInclusion(Include.NON_NULL);
|
||||
// Token Request
|
||||
GoogleOAuthResponse result = mapper.readValue(resultEntity.getBody(), new TypeReference<GoogleOAuthResponse>() {
|
||||
});
|
||||
|
||||
// ID Token만 추출 (사용자의 정보는 jwt로 인코딩 되어있다)
|
||||
String jwtToken = result.getIdToken();
|
||||
String requestUrl = UriComponentsBuilder.fromHttpUrl("https://oauth2.googleapis.com/tokeninfo")
|
||||
.queryParam("id_token", jwtToken).toUriString();
|
||||
|
||||
String resultJson = restTemplate.getForObject(requestUrl, String.class);
|
||||
|
||||
Map<String, String> userInfo = mapper.readValue(resultJson, new TypeReference<Map<String, String>>() {
|
||||
});
|
||||
System.out.println(userInfo.get("email"));
|
||||
model.addAttribute("token", result.getAccessToken());
|
||||
|
||||
return "redirect:/";
|
||||
}
|
||||
@RequestMapping(value = "/login/kakaoCallback.do")
|
||||
public ModelAndView kakaoCallback(@RequestParam("code") String code, HttpServletRequest request, HttpServletResponse response, HttpSession session)
|
||||
throws Exception {
|
||||
ModelAndView mav = new ModelAndView();
|
||||
// 결과값을 node에 담아줌
|
||||
String k_redirect_url="http://nlib.nculture.org/nlib/login/kakaoCallback.do";
|
||||
JsonNode node = KakaoController.getAccessToken(code,k_redirect_url);
|
||||
// accessToken에 사용자의 로그인한 모든 정보가 들어있음
|
||||
JsonNode accessToken = node.get("access_token");
|
||||
// 사용자의 정보
|
||||
JsonNode userInfo = KakaoController.getKakaoUserInfo(accessToken);
|
||||
String kemail = null;
|
||||
String kname = null;
|
||||
String kgender = null;
|
||||
String kbirthday = null;
|
||||
String kage = null;
|
||||
String kimage = null;
|
||||
// 유저정보 카카오에서 가져오기Get properties
|
||||
JsonNode properties = userInfo.path("properties");
|
||||
JsonNode kakao_account = userInfo.path("kakao_account");
|
||||
kemail = kakao_account.path("email").asText();
|
||||
kname = properties.path("nickname").asText();
|
||||
kimage = properties.path("profile_image").asText();
|
||||
kgender = kakao_account.path("gender").asText();
|
||||
kbirthday = kakao_account.path("birthday").asText();
|
||||
kage = kakao_account.path("age_range").asText();
|
||||
session.setAttribute("kemail", kemail);
|
||||
session.setAttribute("kname", kname);
|
||||
session.setAttribute("kimage", kimage);
|
||||
session.setAttribute("kgender", kgender);
|
||||
session.setAttribute("kbirthday", kbirthday);
|
||||
session.setAttribute("kage", kage);
|
||||
mav.setViewName("main");
|
||||
return mav;
|
||||
}// end kakaoLogin()
|
||||
|
||||
// @RequestMapping("/login/loginForm_BK20210817.do")
|
||||
// public String loginForm_BK20210817(HttpServletRequest req, @RequestParam(required = false) String error,
|
||||
// @RequestParam(required = false) String logout, Model model, HttpSession session) {
|
||||
// if (error != null) {
|
||||
// model.addAttribute("error", String.format("ID와 비밀번호를 확인하여 주시기 바랍니다. %s", error));
|
||||
// }
|
||||
// if (logout != null) {
|
||||
// model.addAttribute("logout", String.format("로그아웃하였습니다 %s", logout));
|
||||
// }
|
||||
// // 네이버 로그인 URL 생성
|
||||
// /* 네이버아이디로 인증 URL을 생성하기 위하여 naverLoginBO클래스의 getAuthorizationUrl메소드 호출 */
|
||||
// naverLoginBO.setRedirect_url("http://nlib.nculture.org/nlib/login/naverCallback.do");
|
||||
// String naverAuthUrl = naverLoginBO.getAuthorizationUrl(session);
|
||||
//
|
||||
// // 구글 로그인 URL 생성
|
||||
// String googleUrl = "https://accounts.google.com/o/oauth2/v2/auth?"
|
||||
// + "client_id=879126511006-jro7bld7b2epl3n5mkksp0p24k2inbpu.apps.googleusercontent.com"
|
||||
// + "&redirect_uri=http://nlib.nculture.org/nlib/login/googleCallback.do"
|
||||
// + "&response_type=code"
|
||||
// + "&scope=email%20profile%20openid"
|
||||
// + "&access_type=offline";
|
||||
//
|
||||
// // 카카오 로그인 URL 생성
|
||||
// String k_redirect_url="http://nlib.nculture.org/nlib/login/kakaoCallback.do";
|
||||
// String kakaoUrl = KakaoController.getAuthorizationUrl(session,k_redirect_url);
|
||||
//
|
||||
// model.addAttribute("naverUrl", naverAuthUrl);
|
||||
// model.addAttribute("googleUrl", googleUrl);
|
||||
// model.addAttribute("kakaoUrl", kakaoUrl);
|
||||
//
|
||||
// return "nlib/login/loginForm";
|
||||
// }
|
||||
//
|
||||
@RequestMapping(value = "/login/{oauthService}Callback.do", method = { RequestMethod.GET, RequestMethod.POST})
|
||||
public String oauthLoginCallback(@PathVariable String oauthService,
|
||||
Model model, @RequestParam String code, HttpSession session) throws Exception {
|
||||
|
||||
String redirectUrl = "/index.do";
|
||||
|
||||
log.debug("oauthLoginCallback: service={}", oauthService);
|
||||
log.debug("===>>> code = "+ code);
|
||||
|
||||
OAuthVO oauthVO = null;
|
||||
if (StringUtils.equals(OAuthConfig.GOOGLE_SERVICE_NAME, oauthService))
|
||||
oauthVO = googleAuthVO;
|
||||
else if (StringUtils.equals(OAuthConfig.NAVER_SERVICE_NAME, oauthService))
|
||||
oauthVO = naverAuthVO;
|
||||
else if (StringUtils.equals(OAuthConfig.KAKAO_SERVICE_NAME, oauthService))
|
||||
oauthVO = kakaoAuthVO;
|
||||
else {
|
||||
throw new Exception("SNS 연동 콜백정보가 올바르지 않습니다.");
|
||||
}
|
||||
|
||||
// 1. code를 이용해서 Access Token 받기
|
||||
// 2. Access Token을 이용해서 사용자 제공정보 가져오기
|
||||
OAuthLogin oauthLogin = new OAuthLogin(oauthVO);
|
||||
|
||||
OAuthUniversalUser oauthUser = oauthLogin.getUserProfile(code); // 1,2번 동시
|
||||
log.debug("Profile ===>>" + oauthUser);
|
||||
|
||||
String resultDBInfo = loginService.loginOauth(oauthUser.getUid());
|
||||
|
||||
// oAuth를 통한 SNS연동이 실패한 경우
|
||||
if(oauthUser == null || !oauthUser.isValid()) {
|
||||
model.addAttribute("code", "NOMEM");
|
||||
model.addAttribute("message", "먼저 회원가입하신 후, 이용하여 주시기 바랍니다.");
|
||||
}
|
||||
// SNS 로그인은 정상적이나, NLIB 시스템에 등록되지 않은 사용자 : 회원가입으로 전환
|
||||
else if(oauthUser.isValid() && resultDBInfo == null) {
|
||||
model.addAttribute("code", "GONEW");
|
||||
model.addAttribute("message", "먼저 회원가입하신 후, 이용 가능합니다. 해당 SNS 계정 정보로 회원가입을 진행하시겠습니까?");
|
||||
}
|
||||
// 정상 SNS 연동 로그인
|
||||
else if(oauthUser.isValid() && resultDBInfo != null) {
|
||||
// 세션에 설정된 redirect 주소 확인
|
||||
model.addAttribute("message", "정상적으로 로그인되었습니다.");
|
||||
}
|
||||
return "redirect:" + redirectUrl;
|
||||
}
|
||||
|
||||
// 네이버 로그인 성공시 callback호출 메소드
|
||||
// @RequestMapping(value = "/login/naverCallback_BK20210817.do", method = { RequestMethod.GET, RequestMethod.POST })
|
||||
// public String naverCallback_BK20210817(Model model, @RequestParam String code, @RequestParam String state, HttpSession session)
|
||||
// throws IOException, ParseException {
|
||||
// OAuth2AccessToken oauthToken;
|
||||
// oauthToken = naverLoginBO.getAccessToken(session, code, state);
|
||||
// // 로그인 사용자 정보를 읽어온다.
|
||||
// apiResult = naverLoginBO.getUserProfile(oauthToken);
|
||||
// JSONParser parser = new JSONParser();
|
||||
// Object obj = parser.parse(apiResult);
|
||||
// JSONObject jsonObj = (JSONObject) obj;
|
||||
// JSONObject response_obj = (JSONObject) jsonObj.get("response");
|
||||
// String email = (String) response_obj.get("email");
|
||||
// model.addAttribute("result", apiResult);
|
||||
//
|
||||
// /* 네이버 로그인 성공 페이지 View 호출 */
|
||||
// return "naverSuccess";
|
||||
// }
|
||||
//
|
||||
// // 구글 로그인 콜백
|
||||
// @RequestMapping(value = "/login/googleCallback.do")
|
||||
// public String googleCallback(@RequestParam(value = "code") String authCode, HttpSession session, Model model,
|
||||
// HttpServletRequest request) throws Exception {
|
||||
//
|
||||
// String code = request.getParameter("code");
|
||||
// HttpHeaders headers = new HttpHeaders();
|
||||
// RestTemplate restTemplate = new RestTemplate();
|
||||
// headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
//
|
||||
// MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
|
||||
// parameters.add("code", code);
|
||||
// parameters.add("client_id", "879126511006-jro7bld7b2epl3n5mkksp0p24k2inbpu.apps.googleusercontent.com");
|
||||
// parameters.add("client_secret", "F6T-ZV9jibLhKtcugxPUtBlN");
|
||||
// parameters.add("redirect_uri", "http://nlib.nculture.org/nlib/login/googleCallback.do");
|
||||
// parameters.add("grant_type", "authorization_code");
|
||||
//
|
||||
// HttpEntity<MultiValueMap<String,String>> rest_request = new HttpEntity<>(parameters,headers);
|
||||
//
|
||||
// URI uri = URI.create("https://www.googleapis.com/oauth2/v4/token");
|
||||
//
|
||||
// ResponseEntity<String> resultEntity;
|
||||
// resultEntity = restTemplate.postForEntity(uri, rest_request, String.class);
|
||||
// // JSON 파싱을 위한 기본값 세팅
|
||||
// // 요청시 파라미터는 스네이크 케이스로 세팅되므로 Object mapper에 미리 설정해준다.
|
||||
// ObjectMapper mapper = new ObjectMapper();
|
||||
// mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
|
||||
// mapper.setSerializationInclusion(Include.NON_NULL);
|
||||
// // Token Request
|
||||
// GoogleOAuthResponse result = mapper.readValue(resultEntity.getBody(), new TypeReference<GoogleOAuthResponse>() {
|
||||
// });
|
||||
//
|
||||
// // ID Token만 추출 (사용자의 정보는 jwt로 인코딩 되어있다)
|
||||
// String jwtToken = result.getIdToken();
|
||||
// String requestUrl = UriComponentsBuilder.fromHttpUrl("https://oauth2.googleapis.com/tokeninfo")
|
||||
// .queryParam("id_token", jwtToken).toUriString();
|
||||
//
|
||||
// String resultJson = restTemplate.getForObject(requestUrl, String.class);
|
||||
//
|
||||
// Map<String, String> userInfo = mapper.readValue(resultJson, new TypeReference<Map<String, String>>() {
|
||||
// });
|
||||
// System.out.println(userInfo.get("email"));
|
||||
// model.addAttribute("token", result.getAccessToken());
|
||||
//
|
||||
// return "redirect:/";
|
||||
// }
|
||||
// @RequestMapping(value = "/login/kakaoCallback.do")
|
||||
// public ModelAndView kakaoCallback(@RequestParam("code") String code, HttpServletRequest request, HttpServletResponse response, HttpSession session)
|
||||
// throws Exception {
|
||||
// ModelAndView mav = new ModelAndView();
|
||||
// // 결과값을 node에 담아줌
|
||||
// String k_redirect_url="http://nlib.nculture.org/nlib/login/kakaoCallback.do";
|
||||
// JsonNode node = KakaoController.getAccessToken(code,k_redirect_url);
|
||||
// // accessToken에 사용자의 로그인한 모든 정보가 들어있음
|
||||
// JsonNode accessToken = node.get("access_token");
|
||||
// // 사용자의 정보
|
||||
// JsonNode userInfo = KakaoController.getKakaoUserInfo(accessToken);
|
||||
// String kemail = null;
|
||||
// String kname = null;
|
||||
// String kgender = null;
|
||||
// String kbirthday = null;
|
||||
// String kage = null;
|
||||
// String kimage = null;
|
||||
// // 유저정보 카카오에서 가져오기Get properties
|
||||
// JsonNode properties = userInfo.path("properties");
|
||||
// JsonNode kakao_account = userInfo.path("kakao_account");
|
||||
// kemail = kakao_account.path("email").asText();
|
||||
// kname = properties.path("nickname").asText();
|
||||
// kimage = properties.path("profile_image").asText();
|
||||
// kgender = kakao_account.path("gender").asText();
|
||||
// kbirthday = kakao_account.path("birthday").asText();
|
||||
// kage = kakao_account.path("age_range").asText();
|
||||
// session.setAttribute("kemail", kemail);
|
||||
// session.setAttribute("kname", kname);
|
||||
// session.setAttribute("kimage", kimage);
|
||||
// session.setAttribute("kgender", kgender);
|
||||
// session.setAttribute("kbirthday", kbirthday);
|
||||
// session.setAttribute("kage", kage);
|
||||
// mav.setViewName("main");
|
||||
// return mav;
|
||||
// }// end kakaoLogin()
|
||||
//
|
||||
|
||||
/**
|
||||
* 로그인을 처리한다. (스프링 시큐리티 로그인 수행)
|
||||
|
||||
@ -6,25 +6,25 @@
|
||||
<!-- NAVER OAuth Configuration -->
|
||||
<bean id="naverAuthVO" class="egovframework.com.ext.oauth.service.OAuthVO">
|
||||
<constructor-arg value="naver" /><!-- Service Name -->
|
||||
<constructor-arg value="2NUTY4QHkWzCuEA3dNJo" /><!-- naverClientID -->
|
||||
<constructor-arg value="I4UqcbjJbW" /><!-- naverClientSecret -->
|
||||
<constructor-arg value="http://127.0.0.1:8500/auth/naver/callback" /><!-- naverRedirectUrl -->
|
||||
<constructor-arg value="jefkoYhSfrQ3TtZz5mTp" /><!-- naverClientID -->
|
||||
<constructor-arg value="E2qAGaLEaG" /><!-- naverClientSecret -->
|
||||
<constructor-arg value="http://nlib.nculture.org/nlib/login/naverCallback.do" /><!-- naverRedirectUrl -->
|
||||
</bean>
|
||||
|
||||
<!-- GOOGLE OAuth Configuration -->
|
||||
<bean id="googleAuthVO" class="egovframework.com.ext.oauth.service.OAuthVO">
|
||||
<constructor-arg value="google" /><!-- Service Name -->
|
||||
<constructor-arg value="1044767185911-oev6uo5pkro2n5u3se4lragkb9o8ipg7.apps.googleusercontent.com" /><!-- googleClientID -->
|
||||
<constructor-arg value="879126511006-jro7bld7b2epl3n5mkksp0p24k2inbpu.apps.googleusercontent.com" /><!-- googleClientID -->
|
||||
<constructor-arg value="5qAMYyDD9CkN3f38w0a8zomn" /><!-- googleClientSecret -->
|
||||
<constructor-arg value="http://localhost:8500/auth/google/callback" /><!-- googleRedirectUrl -->
|
||||
<constructor-arg value="http://nlib.nculture.org/nlib/login/googleCallback.do" /><!-- googleRedirectUrl -->
|
||||
</bean>
|
||||
|
||||
<!-- KAKAO OAuth Configuration -->
|
||||
<bean id="kakaoAuthVO" class="egovframework.com.ext.oauth.service.OAuthVO">
|
||||
<constructor-arg value="kakao" /><!-- Service Name -->
|
||||
<constructor-arg value="8fc0e5fc8b29f5224f7ee2101c6e3547" /><!-- kakaoClientID -->
|
||||
<constructor-arg value="e74d25210853313dd1fead4c6c1f06ec" /><!-- kakaoClientID -->
|
||||
<constructor-arg value="AGxiWEwu2ytIifA1AY2PoqVSrdnRZiao" /><!-- kakaoClientSecret -->
|
||||
<constructor-arg value="http://localhost:8500/auth/kakao/callback" /><!-- kakaoRedirectUrl -->
|
||||
<constructor-arg value="http://nlib.nculture.org/nlib/login/kakaoCallback.do" /><!-- kakaoRedirectUrl -->
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
|
||||
@ -10,9 +10,12 @@
|
||||
<ul class="gnb-right">
|
||||
<li><a href="#" onclick="javascript:location.href='${pageContext.request.contextPath}/inform/selectPrivacyInfo.do';">개인정보처리방침</a></li>
|
||||
<li><a href="#" onclick="javascript:location.href='${pageContext.request.contextPath}/inform/selectTermsInfo.do';">이용약관</a></li>
|
||||
|
||||
<li><a href="#" onclick="javascript:location.href='${pageContext.request.contextPath}/login/loginForm.do';">로그인</a></li>
|
||||
<sec:authorize access="not isAuthenticated()">
|
||||
<li><a href="#" onclick="javascript:location.href='${pageContext.request.contextPath}/login/loginForm.do';">로그인</a></li>
|
||||
</sec:authorize>
|
||||
|
||||
<sec:authorize access="isAuthenticated()">
|
||||
<li><a href="#" onclick="javascript:location.href='${pageContext.request.contextPath}/userInfo/getMyInfo.do';">내 정보</a></li>
|
||||
<li><a href="#" onclick="javascript:location.href='${pageContext.request.contextPath}/logout';">로그아웃</a></li>
|
||||
|
||||
Loading…
Reference in New Issue
Block a user