Skip to content

Commit

Permalink
feat: OAuth2 인가 구현
Browse files Browse the repository at this point in the history
- 패키지 이름 auth -> oauth2 수정
- 카카오 인증 서버 프로필 정보 요청 성공
- DB 반영

resolve : #27
  • Loading branch information
BinarySstar committed Jan 4, 2025
1 parent ab53ca8 commit 1161b9c
Show file tree
Hide file tree
Showing 10 changed files with 51 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,16 @@ public class Member extends BaseTimeEntity {
@Setter
private String profileImage;

@Column(name = "registration_id")
private String registrationId;

@Builder
public Member(Long kakaoId, String nickname, String email, String profileImage) {
public Member(Long kakaoId, String nickname, String email, String profileImage, String registrationId) {
this.kakaoId = kakaoId;
this.nickname = nickname;
this.email = email;
this.profileImage = profileImage;
this.registrationId = registrationId;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@
@Repository
public interface MemberRepository extends JpaRepository<Member, Long> {
Optional<Member> findByEmail(String email);

Optional<Member> findByRegistrationIdAndEmail(String registrationId, String email);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
import univ.goormthon.kongju.domain.member.dto.response.ProfileInfo;
import univ.goormthon.kongju.domain.member.entity.Member;
import univ.goormthon.kongju.domain.member.repository.MemberRepository;
import univ.goormthon.kongju.global.auth.kakao.dto.KakaoProfileInfoResponse;
import univ.goormthon.kongju.global.oauth2.kakao.dto.KakaoProfileInfoResponse;
import univ.goormthon.kongju.global.exception.NotFoundException;
import univ.goormthon.kongju.global.exception.dto.ErrorCode;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class MemberService {
Expand All @@ -27,6 +29,12 @@ public Member findOrRegisterMember(String email, KakaoProfileInfoResponse respon
.orElseGet(() -> registerMember(response));
}

@Transactional
public Member findOrRegisterMember(String registrationId, Map<String, Object> attributes) {
return memberRepository.findByRegistrationIdAndEmail(registrationId, (String) attributes.get("email"))
.orElseGet(() -> registerMember(registrationId, attributes));
}

private Member registerMember(KakaoProfileInfoResponse response) {
Member member = Member.builder()
.kakaoId(response.id())
Expand All @@ -37,6 +45,22 @@ private Member registerMember(KakaoProfileInfoResponse response) {
return memberRepository.save(member);
}

private Member registerMember(String registrationId, Map<String, Object> attributes) {
Map<String, Object> kakaoAccount = (Map<String, Object>) attributes.get("kakao_account");
Map<String, Object> properties = (Map<String, Object>) attributes.get("properties");

Member member = Member.builder()
.kakaoId(Long.valueOf(attributes.get("id").toString()))
.email((String) kakaoAccount.get("email"))
.nickname((String) properties.get("nickname"))
.profileImage((String) properties.get("profile_image"))
.registrationId(registrationId)
.build();

return memberRepository.save(member);
}


private Member updateProfileIfChanged(Member member, KakaoProfileInfoResponse profileInfo) {
boolean isChanged = false;
String nickname = profileInfo.kakaoAccount().profile().nickname();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.web.SecurityFilterChain;
import univ.goormthon.kongju.global.auth.CustomOAuth2UserService;
import univ.goormthon.kongju.global.auth.CustomRequestEntityConverter;
import univ.goormthon.kongju.global.oauth2.CustomOAuth2UserService;
import univ.goormthon.kongju.global.oauth2.CustomRequestEntityConverter;

@Configuration
@RequiredArgsConstructor
Expand All @@ -23,9 +24,11 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
http
.csrf(AbstractHttpConfigurer::disable) // 브라우저 환경이 아니므로 CSRF 보호 기능 비활성화
.authorizeHttpRequests(requests -> requests
.requestMatchers("/api/kongju/oauth2/**", "/api/kongju/auth/**").permitAll()
.requestMatchers("/h2-console/**","/swagger-ui.html","/swagger-ui/**", "/api/kongju/oauth2/**", "/api/kongju/auth/**").permitAll()
.anyRequest().authenticated()
)
.headers(headers -> headers
.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
.oauth2Login(oauth2 -> oauth2
.userInfoEndpoint(userInfo -> userInfo
.userService(customOAuth2UserService))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package univ.goormthon.kongju.global.auth;
package univ.goormthon.kongju.global.oauth2;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package univ.goormthon.kongju.global.auth;
package univ.goormthon.kongju.global.oauth2;

import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
Expand All @@ -8,35 +8,31 @@
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import univ.goormthon.kongju.domain.member.entity.Member;
import univ.goormthon.kongju.domain.member.service.MemberService;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class CustomOAuth2UserService extends DefaultOAuth2UserService {

// private final MemberRepository memberRepository;
private final MemberService memberService;

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

// 사용자 정보 추출
String registrationId = userRequest.getClientRegistration().getRegistrationId();
String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails()
.getUserInfoEndpoint().getUserNameAttributeName();
String userNameAttributeName = userRequest.getClientRegistration()
.getProviderDetails()
.getUserInfoEndpoint()
.getUserNameAttributeName();
Map<String, Object> attributes = oAuth2User.getAttributes();

System.out.println(attributes);
memberService.findOrRegisterMember(registrationId, attributes);

return new DefaultOAuth2User(oAuth2User.getAuthorities(), attributes, userNameAttributeName);
}


// 가입하지 않은 사용자는 Member 객체를 새로 생성하여 DB에 저장
private Member getMember() {
return null;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package univ.goormthon.kongju.global.auth;
package univ.goormthon.kongju.global.oauth2;

import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package univ.goormthon.kongju.global.auth;
package univ.goormthon.kongju.global.oauth2;

import java.util.Map;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package univ.goormthon.kongju.global.auth.kakao.dto;
package univ.goormthon.kongju.global.oauth2.kakao.dto;

import com.fasterxml.jackson.annotation.JsonProperty;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package univ.goormthon.kongju.global.auth.kakao.dto;
package univ.goormthon.kongju.global.oauth2.kakao.dto;

import com.fasterxml.jackson.annotation.JsonProperty;

Expand Down

0 comments on commit 1161b9c

Please sign in to comment.