Skip to content

Commit

Permalink
✨practice(#10) : OAuth2를 활용한 카카오 소셜 로그인 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
2ghrms committed Dec 2, 2024
1 parent 156410f commit abaa87d
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 1 deletion.
3 changes: 3 additions & 0 deletions spring/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
testImplementation 'org.springframework.security:spring-security-test'

// Spring Security OAuth2 클라이언트 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'

//Thymeleaf
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6:3.1.1.RELEASE'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package umc.spring.config.security;

import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import umc.spring.domain.Member;
import umc.spring.domain.enums.Gender;
import umc.spring.domain.enums.Role;
import umc.spring.repository.MemberRepository.MemberRepository;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class CustomOAuth2UserService extends DefaultOAuth2UserService {

private final MemberRepository memberRepository;
private final PasswordEncoder passwordEncoder;

@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(userRequest);

Map<String, Object> attributes = oAuth2User.getAttributes();
Map<String, Object> properties = (Map<String, Object>) attributes.get("properties");

String nickname = (String) properties.get("nickname");
String email = nickname + "@kakao.com"; // 임시 이메일 생성

// 사용자 정보 저장 또는 업데이트
Member member = saveOrUpdateUser(email, nickname);

// 이메일을 Principal로 사용하기 위해 attributes 수정
Map<String, Object> modifiedAttributes = new HashMap<>(attributes);
modifiedAttributes.put("email", email);

return new DefaultOAuth2User(
oAuth2User.getAuthorities(),
modifiedAttributes,
"email" // email Principal로 설정
);
}

private Member saveOrUpdateUser(String email, String nickname) {
Member member = memberRepository.findByEmail(email)
.orElse(Member.builder()
.email(email)
.name(nickname)
.password(passwordEncoder.encode("OAUTH_USER_" + UUID.randomUUID()))
.gender(Gender.NONE) // 기본값 설정
.address("소셜로그인") // 기본값 설정
.specAddress("소셜로그인") // 기본값 설정
.role(Role.USER)
.build());

return memberRepository.save(member);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.defaultSuccessUrl("/home", true)
.permitAll()
)
.oauth2Login(oauth2 -> oauth2
.loginPage("/login")
.defaultSuccessUrl("/home", true)
.permitAll()
)
.logout((logout) -> logout
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
Expand Down
20 changes: 19 additions & 1 deletion spring/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,22 @@ spring:
use_sql_comments: true
hbm2ddl:
auto: update
default_batch_fetch_size: 1000
default_batch_fetch_size: 1000
security:
oauth2:
client:
registration:
kakao:
client-authentication-method: client_secret_post
client-id: b520cf6225bb08837856b4bcee2232be
client-secret: 5lBI2OF2hvUBAUHbG2QSUuFeyDCGb6Yn
redirect-uri: http://localhost:8080/login/oauth2/code/kakao
authorization-grant-type: authorization_code
scope: profile_nickname
client-name: Kakao
provider:
kakao:
authorization-uri: https://kauth.kakao.com/oauth/authorize
token-uri: https://kauth.kakao.com/oauth/token
user-info-uri: https://kapi.kakao.com/v2/user/me
user-name-attribute: id
1 change: 1 addition & 0 deletions spring/src/main/resources/templates/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ <h2>Login</h2>
<p th:if="${param.logout}">로그아웃되었습니다.</p>
<!-- 회원가입 링크 수정 -->
<p>계정이 없나요? <a th:href="@{/signup}">Sign up</a></p>
<a th:href="@{/oauth2/authorization/kakao}">카카오로 로그인</a>
</body>
</html>

0 comments on commit abaa87d

Please sign in to comment.