Merge pull request #8 from codej99/feature/social-kakao

Feature/social kakao
This commit is contained in:
codej99
2019-04-19 11:01:10 +09:00
committed by GitHub
21 changed files with 370 additions and 18 deletions

View File

@@ -67,4 +67,9 @@
- Document
- https://daddyprogrammer.org/post/938/springboot2-restapi-unit-test/
- Git
- https://github.com/codej99/SpringRestApi/tree/feature/junit-test
- https://github.com/codej99/SpringRestApi/tree/feature/junit-test
- SpringBoot2로 Rest api 만들기(10) Social Login kakao
- Document
- https://daddyprogrammer.org/post/1012/springboot2-rest-api-social-login-kakao/
- Git
- https://github.com/codej99/SpringRestApi/tree/feature/social-kakao

View File

@@ -29,6 +29,7 @@ dependencies {
implementation 'io.springfox:springfox-swagger2:2.6.1'
implementation 'io.springfox:springfox-swagger-ui:2.6.1'
implementation 'net.rakugakibox.util:yaml-resource-bundle:1.1'
implementation 'com.google.code.gson:gson'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
runtimeOnly 'mysql:mysql-connector-java'

View File

@@ -5,6 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class SpringRestApiApplication {
@@ -16,4 +17,9 @@ public class SpringRestApiApplication {
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}

View File

@@ -1,8 +1,6 @@
package com.rest.api.advice;
import com.rest.api.advice.exception.CAuthenticationEntryPointException;
import com.rest.api.advice.exception.CEmailSigninFailedException;
import com.rest.api.advice.exception.CUserNotFoundException;
import com.rest.api.advice.exception.*;
import com.rest.api.model.response.CommonResult;
import com.rest.api.service.ResponseService;
import lombok.RequiredArgsConstructor;
@@ -55,6 +53,18 @@ public class ExceptionAdvice {
return responseService.getFailResult(Integer.valueOf(getMessage("accessDenied.code")), getMessage("accessDenied.msg"));
}
@ExceptionHandler(CCommunicationException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public CommonResult communicationException(HttpServletRequest request, CCommunicationException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("communicationError.code")), getMessage("communicationError.msg"));
}
@ExceptionHandler(CUserExistException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public CommonResult communicationException(HttpServletRequest request, CUserExistException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("existingUser.code")), getMessage("existingUser.msg"));
}
// code정보에 해당하는 메시지를 조회합니다.
private String getMessage(String code) {
return getMessage(code, null);

View File

@@ -0,0 +1,15 @@
package com.rest.api.advice.exception;
public class CCommunicationException extends RuntimeException {
public CCommunicationException(String msg, Throwable t) {
super(msg, t);
}
public CCommunicationException(String msg) {
super(msg);
}
public CCommunicationException() {
super();
}
}

View File

@@ -0,0 +1,15 @@
package com.rest.api.advice.exception;
public class CUserExistException extends RuntimeException {
public CUserExistException(String msg, Throwable t) {
super(msg, t);
}
public CUserExistException(String msg) {
super(msg);
}
public CUserExistException() {
super();
}
}

View File

@@ -31,7 +31,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증할것이므로 세션필요없으므로 생성안함.
.and()
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
.antMatchers("/*/signin", "/*/signup").permitAll() // 가입 및 인증 주소는 누구나 접근가능
.antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
.antMatchers(HttpMethod.GET, "/helloworld/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
.and()

View File

@@ -0,0 +1,60 @@
package com.rest.api.controller.common;
import com.google.gson.Gson;
import com.rest.api.service.social.KakaoService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
@RequiredArgsConstructor
@Controller
@RequestMapping("/social/login")
public class SocialController {
private final Environment env;
private final RestTemplate restTemplate;
private final Gson gson;
private final KakaoService kakaoService;
@Value("${spring.url.base}")
private String baseUrl;
@Value("${spring.social.kakao.client_id}")
private String kakaoClientId;
@Value("${spring.social.kakao.redirect}")
private String kakaoRedirect;
/**
* 카카오 로그인 페이지
*/
@GetMapping
public ModelAndView socialLogin(ModelAndView mav) {
StringBuilder loginUrl = new StringBuilder()
.append(env.getProperty("spring.social.kakao.url.login"))
.append("?client_id=").append(kakaoClientId)
.append("&response_type=code")
.append("&redirect_uri=").append(baseUrl).append(kakaoRedirect);
mav.addObject("loginUrl", loginUrl);
mav.setViewName("social/login");
return mav;
}
/**
* 카카오 인증 완료 후 리다이렉트 화면
*/
@GetMapping(value = "/kakao")
public ModelAndView redirectKakao(ModelAndView mav, @RequestParam String code) {
mav.addObject("authInfo", kakaoService.getKakaoTokenInfo(code));
mav.setViewName("social/redirectKakao");
return mav;
}
}

View File

@@ -1,12 +1,16 @@
package com.rest.api.controller.v1;
import com.rest.api.advice.exception.CEmailSigninFailedException;
import com.rest.api.entity.User;
import com.rest.api.advice.exception.CUserExistException;
import com.rest.api.advice.exception.CUserNotFoundException;
import com.rest.api.config.security.JwtTokenProvider;
import com.rest.api.entity.User;
import com.rest.api.model.response.CommonResult;
import com.rest.api.model.response.SingleResult;
import com.rest.api.model.social.KakaoProfile;
import com.rest.api.repo.UserJpaRepo;
import com.rest.api.service.ResponseService;
import com.rest.api.service.social.KakaoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@@ -15,6 +19,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.Optional;
@Api(tags = {"1. Sign"})
@RequiredArgsConstructor
@@ -26,6 +31,7 @@ public class SignController {
private final JwtTokenProvider jwtTokenProvider;
private final ResponseService responseService;
private final PasswordEncoder passwordEncoder;
private final KakaoService kakaoService;
@ApiOperation(value = "로그인", notes = "이메일 회원 로그인을 한다.")
@PostMapping(value = "/signin")
@@ -39,6 +45,17 @@ public class SignController {
return responseService.getSingleResult(jwtTokenProvider.createToken(String.valueOf(user.getMsrl()), user.getRoles()));
}
@ApiOperation(value = "소셜 로그인", notes = "소셜 회원 로그인을 한다.")
@PostMapping(value = "/signin/{provider}")
public SingleResult<String> signinByProvider(
@ApiParam(value = "서비스 제공자 provider", required = true, defaultValue = "kakao") @PathVariable String provider,
@ApiParam(value = "소셜 access_token", required = true) @RequestParam String accessToken) {
KakaoProfile profile = kakaoService.getKakaoProfile(accessToken);
User user = userJpaRepo.findByUidAndProvider(String.valueOf(profile.getId()), provider).orElseThrow(CUserNotFoundException::new);
return responseService.getSingleResult(jwtTokenProvider.createToken(String.valueOf(user.getMsrl()), user.getRoles()));
}
@ApiOperation(value = "가입", notes = "회원가입을 한다.")
@PostMapping(value = "/signup")
public CommonResult signup(@ApiParam(value = "회원ID : 이메일", required = true) @RequestParam String id,
@@ -53,4 +70,26 @@ public class SignController {
.build());
return responseService.getSuccessResult();
}
@ApiOperation(value = "소셜 계정 가입", notes = "소셜 계정 회원가입을 한다.")
@PostMapping(value = "/signup/{provider}")
public CommonResult signupProvider(@ApiParam(value = "서비스 제공자 provider", required = true, defaultValue = "kakao") @PathVariable String provider,
@ApiParam(value = "소셜 access_token", required = true) @RequestParam String accessToken,
@ApiParam(value = "이름", required = true) @RequestParam String name) {
KakaoProfile profile = kakaoService.getKakaoProfile(accessToken);
Optional<User> user = userJpaRepo.findByUidAndProvider(String.valueOf(profile.getId()), provider);
if (user.isPresent())
throw new CUserExistException();
User inUser = User.builder()
.uid(String.valueOf(profile.getId()))
.provider(provider)
.name(name)
.roles(Collections.singletonList("ROLE_USER"))
.build();
userJpaRepo.save(inUser);
return responseService.getSuccessResult();
}
}

View File

@@ -1,10 +1,7 @@
package com.rest.api.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
@@ -28,10 +25,12 @@ public class User implements UserDetails {
@Column(nullable = false, unique = true, length = 50)
private String uid;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Column(nullable = false, length = 100)
@Column(length = 100)
private String password;
@Column(nullable = false, length = 100)
private String name;
@Column(length = 100)
private String provider;
@ElementCollection(fetch = FetchType.EAGER)
@Builder.Default

View File

@@ -0,0 +1,22 @@
package com.rest.api.model.social;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class KakaoProfile {
private Long id;
private Properties properties;
@Getter
@Setter
@ToString
private static class Properties {
private String nickname;
private String thumbnail_image;
private String profile_image;
}
}

View File

@@ -0,0 +1,14 @@
package com.rest.api.model.social;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RetKakaoAuth {
private String access_token;
private String token_type;
private String refresh_token;
private long expires_in;
private String scope;
}

View File

@@ -7,4 +7,6 @@ import java.util.Optional;
public interface UserJpaRepo extends JpaRepository<User, Long> {
Optional<User> findByUid(String email);
Optional<User> findByUidAndProvider(String uid, String provider);
}

View File

@@ -0,0 +1,70 @@
package com.rest.api.service.social;
import com.google.gson.Gson;
import com.rest.api.advice.exception.CCommunicationException;
import com.rest.api.model.social.KakaoProfile;
import com.rest.api.model.social.RetKakaoAuth;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
@RequiredArgsConstructor
@Service
public class KakaoService {
private final RestTemplate restTemplate;
private final Environment env;
private final Gson gson;
@Value("${spring.url.base}")
private String baseUrl;
@Value("${spring.social.kakao.client_id}")
private String kakaoClientId;
@Value("${spring.social.kakao.redirect}")
private String kakaoRedirect;
public KakaoProfile getKakaoProfile(String accessToken) {
// Set header : Content-type: application/x-www-form-urlencoded
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set("Authorization", "Bearer " + accessToken);
// Set http entity
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(null, headers);
try {
// Request profile
ResponseEntity<String> response = restTemplate.postForEntity(env.getProperty("spring.social.kakao.url.profile"), request, String.class);
if (response.getStatusCode() == HttpStatus.OK)
return gson.fromJson(response.getBody(), KakaoProfile.class);
} catch (Exception e) {
throw new CCommunicationException();
}
throw new CCommunicationException();
}
public RetKakaoAuth getKakaoTokenInfo(String code) {
// Set header : Content-type: application/x-www-form-urlencoded
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// Set parameter
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "authorization_code");
params.add("client_id", kakaoClientId);
params.add("redirect_uri", baseUrl + kakaoRedirect);
params.add("code", code);
// Set http entity
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> response = restTemplate.postForEntity(env.getProperty("spring.social.kakao.url.token"), request, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
return gson.fromJson(response.getBody(), RetKakaoAuth.class);
}
return null;
}
}

View File

@@ -14,4 +14,14 @@ spring:
basename: i18n/exception
encoding: UTF-8
jwt:
secret: govlepel@$&
secret: govlepel@$&
social:
kakao:
client_id: XXXXXXXXXXXXXXXXXXXXXXXXXX # 앱생성시 받은 REST API 키
redirect: /social/login/kakao
url:
login: https://kauth.kakao.com/oauth/authorize
token: https://kauth.kakao.com/oauth/token
profile: https://kapi.kakao.com/v2/user/me
url:
base: http://localhost:8080

View File

@@ -12,4 +12,10 @@ entryPointException:
msg: "You do not have permission to access this resource."
accessDenied:
code: "-1003"
msg: "A resource that can not be accessed with the privileges it has."
msg: "A resource that can not be accessed with the privileges it has."
communicationError:
code: "-1004"
msg: "An error occurred during communication."
existingUser:
code: "-1005"
msg: "You are an existing member."

View File

@@ -12,4 +12,10 @@ entryPointException:
msg: "해당 리소스에 접근하기 위한 권한이 없습니다."
accessDenied:
code: "-1003"
msg: "보유한 권한으로 접근할수 없는 리소스 입니다."
msg: "보유한 권한으로 접근할수 없는 리소스 입니다."
communicationError:
code: "-1004"
msg: "통신 중 오류가 발생하였습니다."
existingUser:
code: "-1005"
msg: "이미 가입한 회원입니다. 로그인을 해주십시오."

View File

@@ -0,0 +1,6 @@
<button onclick="popupKakaoLogin()">KakaoLogin</button>
<script>
function popupKakaoLogin() {
window.open('${loginUrl}', 'popupKakaoLogin', 'width=700,height=500,scrollbars=0,toolbar=0,menubar=no')
}
</script>

View File

@@ -0,0 +1,5 @@
access_token : ${authInfo.access_token}<br>
token_type : ${authInfo.token_type}<br>
refresh_token : ${authInfo.refresh_token}<br>
expires_in : ${authInfo.expires_in}<br>
scope : ${authInfo.scope}<br>

View File

@@ -1,19 +1,16 @@
package com.rest.api.controller.v1;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
import java.time.LocalDateTime;
import java.time.ZoneId;
@@ -86,4 +83,39 @@ public class SignControllerTest {
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.code").value(-9999));
}
@Test
public void signInProviderFail() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("accessToken", "XXXXXXXX");
mockMvc.perform(post("/v1/signin/kakao").params(params))
.andDo(print())
.andExpect(status().is5xxServerError())
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.code").value(-1004));
}
@Test
public void signUpProvider() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("accessToken", "HizF3ir9522bMW3shkO0x0T9zBdXFCW1WsF56Qo9dVsAAAFqMwTqHw");
params.add("name", "kakaoKing!");
mockMvc.perform(post("/v1/signup/kakao").params(params))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.code").value(0));
}
@Test
public void signInProvider() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("accessToken", "HizF3ir9522bMW3shkO0x0T9zBdXFCW1WsF56Qo9dVsAAAFqMwTqHw");
mockMvc.perform(post("/v1/signin/kakao").params(params))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data").exists());
}
}

View File

@@ -0,0 +1,29 @@
package com.rest.api.service.social;
import com.rest.api.model.social.KakaoProfile;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class KakaoServiceTest {
@Autowired
private KakaoService kakaoService;
@Test
public void whenGetKakaoProfile_thenReturnProfile() {
String accessToken = "xjsMzpQtIr4w13FIQvL3R7BW7X4yvm1KmzXCTwopyWAAAAFqMxEcwA";
// given
KakaoProfile profile = kakaoService.getKakaoProfile(accessToken);
// then
assertNotNull(profile);
assertEquals(profile.getId(), Long.valueOf(1066788171));
}
}