Open eunja511005 opened 1 year ago
OAtuth2 의존성 추가
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
의존성 추가
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
application.properties 파일 변경
## KAKAO Login
spring.security.oauth2.client.registration.kakao.client-id=03ef8feea24a093a92736fc82f986513
spring.security.oauth2.client.registration.kakao.redirect-uri={baseUrl}/{action}/oauth2/code/{registrationId}
spring.security.oauth2.client.registration.kakao.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.kakao.scope=profile_nickname, profile_image, account_email, gender
spring.security.oauth2.client.registration.kakao.client-name=kakao
spring.security.oauth2.client.registration.kakao.client-authentication-method=POST
## kAKAO Provider
spring.security.oauth2.client.provider.kakao.authorization-uri= https://kauth.kakao.com/oauth/authorize
spring.security.oauth2.client.provider.kakao.token-uri=https://kauth.kakao.com/oauth/token
spring.security.oauth2.client.provider.kakao.user-info-uri=https://kapi.kakao.com/v2/user/me
spring.security.oauth2.client.provider.kakao.user-name-attribute=id
컨그파일 설정
- 카카오나 구글에서 로그인 성공시 호출될 서비스(customOAuth2UserService) 등록
- 로그인 후 접속 페이지 설정(/main)
private final CustomOAuth2UserService customOAuth2UserService;
http.oauth2Login()
.userInfoEndpoint()
.userService(customOAuth2UserService)
.and()
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
log.info("userInfo {}", authentication.getPrincipal().toString());
log.info("authentication {}", authentication.toString());
log.info("authentication Name {}", authentication.getName());
response.sendRedirect("/main");
}
});
로그인 시 호출 서비스 개발(customOAuth2UserService)
// 카카오나 구글에서 보내준 정보로 유저 있는지 조회해서 있으면 반환하고 없으면 생성 한다.
// 생성시 기본 유저롤을 부여 한다.
private UserInfoDTO saveOrUpdate(OAuthAttributes attributes){
Map<String, Object> map = new HashMap<>();
map.put("username", attributes.getName()); // 가져온 데이터에 키와 벨류값을 지정
UserInfoDTO userInfoDTO = testDao.getUser(map);
if(userInfoDTO == null) {
userInfoDTO = UserInfoDTO.builder().createId("OAuth2")
.isEnable(true)
.username(attributes.getName())
.email(attributes.getEmail())
.picture(attributes.getPicture())
.role("ROLE_USER")
.build();
userDao.addUser(userInfoDTO);
}
return userInfoDTO;
}
OAuthAttributes
public static OAuthAttributes of(String registrationId, String userNameAttributeName, Map<String, Object> attributes){
// 여기서 네이버와 카카오 등 구분 (ofNaver, ofKakao)
if("github".equals(registrationId)){
return ofGithub("id", attributes);
}
if("kakao".equals(registrationId)){
return ofKakao("id", attributes);
}
if("google".equals(registrationId)){
return ofGoogle(userNameAttributeName, attributes);
}
return null;
}
private static OAuthAttributes ofKakao(String userNameAttributeName, Map<String, Object> attributes) {
Map<String,Object> response = (Map<String, Object>)attributes.get("kakao_account");
Map<String, Object> profile = (Map<String, Object>) response.get("profile");
return OAuthAttributes.builder()
.name((String)profile.get("nickname"))
.email((String)response.get("email"))
.picture((String)profile.get("thumbnail_image_url"))
.attributes(attributes)
.nameAttributeKey(userNameAttributeName)
.build();
}
화면에 카카오톡 버튼 추가(중요 : /oauth2/authorization/kakao)
<div class="container px-5 mb-3">
<div class="row justify-content-center">
<a href="/oauth2/authorization/kakao"><img src="https://developers.kakao.com/tool/resource/static/img/button/login/full/ko/kakao_login_medium_narrow.png"></a>
</div>
</div>
Kakao Developers 접속
구글 계정으로 로그인(패스워드는 모바일 메모장에서 확인)
(1) 애플리케이션 추가하기![image](https://github.com/eunja511005/AutoCoding/assets/118089135/a79837c2-582a-4427-99cc-d58fbe039188)
(2) 카카오 로그인 활성화![image](https://github.com/eunja511005/AutoCoding/assets/118089135/6ce0cbb1-ff75-40a5-9dbc-f8dcb80607f3)
(3) Redirect URI 등록(/login/oauth2/code/kakao)
(4) 가져올 정보 선택![image](https://github.com/eunja511005/AutoCoding/assets/118089135/440448c0-697a-424f-9282-2a55eddf3010)
(5) 잘 적용 되었는지 확인 하기 http://localhost:8080/kauth.kakao.com/oauth/authorize?client_id={REST_API_KEY}&redirect_uri={REDIRECT_URI}&response_type=code![image](https://github.com/eunja511005/AutoCoding/assets/118089135/529b8e59-44cf-4af8-b286-72d66595d8ff)