Spring Security :: Oauth JWT(4)

hyunjoon park·2024년 2월 16일
1

Spring Security

목록 보기
12/12

Spring Boot + Security로 Oauth 공부하기 (with JWT)
https://www.youtube.com/watch?v=xsmKOo-sJ3c&list=PLJkjrxxiBSFALedMwcqDw_BPaJ3qqbWeB
개발자 유미님 유튜브를 보고 공부한 내용을 정리한다

UserDto

package spring.oauth.jwt.domain.auth.presentation.dto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class UserDto {
  private String role;
  private String name;
  private String userName;
}

CustomOAuth2UserService 구현완료

package spring.oauth.jwt.domain.auth.service;

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.OAuth2User;
import org.springframework.stereotype.Service;
import spring.oauth.jwt.domain.auth.presentation.dto.CustomOAuth2User;
import spring.oauth.jwt.domain.auth.presentation.dto.OAuth2Response;
import spring.oauth.jwt.domain.auth.presentation.dto.UserDto;
import spring.oauth.jwt.domain.auth.presentation.dto.google.GoogleResponse;

@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
  @Override
  public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
    OAuth2User oAuth2User = super.loadUser(userRequest);
    System.out.println("oAuth2User = " + oAuth2User);

    String registrationId = userRequest.getClientRegistration().getRegistrationId();

    OAuth2Response oAuth2Response = null;
    if (registrationId.equals("google")) {
      oAuth2Response = new GoogleResponse(oAuth2User.getAttributes());
    }

    String userName =
      oAuth2Response.getProvider() + " " + oAuth2Response.getProviderId();

    UserDto userDto = new UserDto();
    userDto.setUserName(userName);
    userDto.setName(oAuth2Response.getName());
    userDto.setRole("ROLE_USER");

    return new CustomOAuth2User(userDto);
  }
}

CustomOAuth2UserDto

package spring.oauth.jwt.domain.auth.presentation.dto;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.user.OAuth2User;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

@RequiredArgsConstructor
public class CustomOAuth2User implements OAuth2User {
  private final UserDto userDto;

  @Override
  public Map<String, Object> getAttributes() {

    return null;
  }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {

    Collection<GrantedAuthority> collection = new ArrayList<>();

    collection.add(new GrantedAuthority() {

      @Override
      public String getAuthority() {

        return userDto.getRole();
      }
    });

    return collection;
  }

  @Override
  public String getName() {

    return userDto.getName();
  }

  public String getUserName() {

    return userDto.getUserName();
  }
}

User 엔티티

package spring.oauth.jwt.domain.user;

import jakarta.persistence.*;
import lombok.*;

@Entity
@Table
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@ToString
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String userName;
  private String name;
  private String email;
  private String role;

  @Builder
  public User(Long id, String userName, String name, String email, String role) {
    this.id = id;
    this.userName = userName;
    this.name = name;
    this.email = email;
    this.role = role;
  }
}

UserRepository

package spring.oauth.jwt.domain.user.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import spring.oauth.jwt.domain.user.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
  User findByUserName(String userName);
}

CustomOAuth2UserService 완성

package spring.oauth.jwt.domain.auth.service;

import lombok.RequiredArgsConstructor;
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.OAuth2User;
import org.springframework.stereotype.Service;
import spring.oauth.jwt.domain.auth.presentation.dto.CustomOAuth2User;
import spring.oauth.jwt.domain.auth.presentation.dto.OAuth2Response;
import spring.oauth.jwt.domain.auth.presentation.dto.UserDto;
import spring.oauth.jwt.domain.auth.presentation.dto.google.GoogleResponse;
import spring.oauth.jwt.domain.user.User;
import spring.oauth.jwt.domain.user.repository.UserRepository;

@Service
@RequiredArgsConstructor
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
  private final UserRepository userRepository;
  @Override
  public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
    OAuth2User oAuth2User = super.loadUser(userRequest);
    System.out.println("oAuth2User = " + oAuth2User);

    String registrationId = userRequest.getClientRegistration().getRegistrationId();

    OAuth2Response oAuth2Response = null;
    if (registrationId.equals("google")) {
      oAuth2Response = new GoogleResponse(oAuth2User.getAttributes());
    }

    String userName =
      oAuth2Response.getProvider() + " " + oAuth2Response.getProviderId();

    User existData = userRepository.findByUserName(userName);

    // 한번도 로그인 하지 않아서 데이터가 없음
    if(existData == null) {
      User user = User.builder()
        .userName(userName)
        .name(oAuth2Response.getName())
        .email(oAuth2Response.getEmail())
        .role("ROLE_USER")
        .build();

      userRepository.save(user);

      UserDto userDto = new UserDto();
      userDto.setUserName(userName);
      userDto.setName(oAuth2Response.getName());
      userDto.setRole("ROLE_USER");

      return new CustomOAuth2User(userDto);
    } else {

      existData.setEmail(oAuth2Response.getEmail());
      existData.setName(oAuth2Response.getName());

      userRepository.save(existData);

      UserDto userDTO = new UserDto();
      userDTO.setUserName(existData.getUserName());
      userDTO.setName(oAuth2Response.getName());
      userDTO.setRole(existData.getRole());

      return new CustomOAuth2User(userDTO);
    }
  }
}
profile
Backend Developer

0개의 댓글