프로젝트

스프링 부트 프로젝트(소셜로그인)

이제하네 2024. 6. 16. 00:57

소셜로그인을 하기 위해서는 해당 사이트에 먼저 설정할 필요가 있다.   application.properties  부분

# KaKao OAuth2 
spring.security.oauth2.client.registration.kakao.client-id= 자기 클라이언트 ID
spring.security.oauth2.client.registration.kakao.client-secret= 비밀 KEY
spring.security.oauth2.client.registration.kakao.redirect-uri={baseUrl}/oauth2/callback/{registrationId}
spring.security.oauth2.client.registration.kakao.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.kakao.client-authentication-method=client_secret_post
spring.security.oauth2.client.registration.kakao.scope=profile_nickname, account_email, name, phone_number

# KaKao OAuth2 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

# Naver OAuth2 
spring.security.oauth2.client.registration.naver.client-id= 자기 클라이언트 ID
spring.security.oauth2.client.registration.naver.client-secret= 비밀 KEY
spring.security.oauth2.client.registration.naver.redirect-uri={baseUrl}/oauth2/callback/{registrationId}
spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.naver.scope=email, name, nickname, phone_number

# Naver OAuth2 Provider 
spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2.0/authorize
spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2.0/token
spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me
spring.security.oauth2.client.provider.naver.user-name-attribute=response

ServiceImpl 부분

 

@Service
@RequiredArgsConstructor
@Slf4j
public class OAuth2UserServiceImpl extends DefaultOAuth2UserService {

    private final MemberRepository memberRepository;

    @Override
    public OAuth2User loadUser(OAuth2UserRequest request) throws OAuth2AuthenticationException{

        OAuth2User oAuth2User = super.loadUser(request);
        String oauthClientName = request.getClientRegistration().getClientName();

        
        try { // 단순히 무엇을 가져왔는지 체크하기위해 존재  나중에 필히 삭제해야됨
            log.info(new ObjectMapper().writeValueAsString(oAuth2User.getAttributes()));
        } catch (Exception exception){
            exception.printStackTrace();
        }

        Member member = null;
        String email = "";

        if (oauthClientName.equals("kakao")){
            Map<String,String> properties = (Map<String,String>)oAuth2User.getAttributes().get("properties");

            Map<String,String> kakaoAccount = (Map<String,String>)oAuth2User.getAttributes().get("kakao_account");
            email = kakaoAccount.get("email");
            String name = kakaoAccount.get("name");
            //전화번호를 00000000000 이런형식으로 저장되기위해 이렇게 고침
            String phoneNumber = kakaoAccount.get("phone_number").replace("+82 ","0").replaceAll("-" , "");
            String nickname = properties.get("nickname");


            member = Member.createKakao(email,name, phoneNumber ,nickname );
            log.info("member >>>"  + member.toString());
        }
        if (oauthClientName.equals("naver")){
            Map<String,String> responseMap = (Map<String,String>)oAuth2User.getAttributes().get("response");
            email = responseMap.get("email");
            String name = responseMap.get("name");
            String nickname = responseMap.get("nickname");
            //전화번호를 00000000000 이런형식으로 저장되기위해 이렇게 고침
            String phoneNumber = responseMap.get("mobile").replaceAll("-" , "");

            member = Member.createNaver(email , name, nickname, phoneNumber);
            log.info("member >>>"  + member.toString());
        }

        Member checkMember = memberRepository.findByEmail(email);

        if(checkMember == null) {
            memberRepository.saveMember(member.getName(), member.getEmail(), member.getPassword(),
                    member.getNickname(), member.getPhoneNumber(), member.getSignType());

        }
        return new Oauth2Member(member.getEmail());
    }
}

 

domain 부분

@NoArgsConstructor
@AllArgsConstructor
public class Oauth2Member implements OAuth2User {

    private  String email;

    @Override
    public Map<String, Object> getAttributes() {
        return null;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getName() {
        return  this.email;
    }
}

 

handler 부분

@Component
@RequiredArgsConstructor
public class OAuth2SuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private final JwtProvider jwtProvider;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        Oauth2Member oauth2Member = (Oauth2Member)authentication.getPrincipal();

        String email = oauth2Member.getName();
        String token = jwtProvider.create(email);

        response.sendRedirect("http://localhost:3000/auth/oauth-repsonse/" + token);
    }
}

로그인이 성공하면 헤더 부분에 token을 넣어서 프론트에 넘겨줌

주소에
localhost:8080/api/member/oauth2/kakao -> 카카오 소셜로그인
localhost:8080/api/member/oauth2/naver  ->네이버 소셜로그인

해당 주소로 들어가면 이런 화면이 뜸

 

해당 주소로 들어가면 이런 화면이 뜸

 

그리고 로그인을 하면 헤더부분에 
http://localhost:3000/auth/oauth-repsonse/eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzYnNka3NzdWRAZ21haWwuY29tIiwiaWF0IjoxNzE4NDY2OTEzLCJleHAiOjE3MTg0NjY5NzN9.LHx-9B4dqTD7_E6Vqri-1tltFHO1EQ7bj0vezv2MG1E
이렇게 들어오는데 repsonse/뒷 부분이 JWT 토큰 부분

'프로젝트' 카테고리의 다른 글

스프링 부트 프로젝트(로그인)  (0) 2024.06.03
스프링 부트 프로젝트 (회원 가입)  (0) 2024.05.29