Spring Security 와 OAuth 간편 로그인 서비스 구현

JungWooLee·2022년 8월 9일
1

SpringBoot ToyProject

목록 보기
4/14

이어서 진행하기

1. Spring Security 알아보기

  • OAuth 로그인 방식을 채택할것이기에 스프링 시큐리티를 채택하였습니다

2. 구글 OAuth 진행하기

  • 다양한 OAuth가 있는데 그중 구글 로그인 방식을 사전에 테스트합니다

Spring Security 란?

스프링 시큐리티는 막강한 인증과 인가 기능을 가진 프레임워크입니다

  • 스프링 기반 애플리케이션에서는 보안을 위한 표준이 됩니다
  • 기존 인터셉터, 필터 기반의 보안기능을 구현하는 것보다 스프링 시큐리티를 통해 구현하는것을 적극 권장합니다
  • 확장성을 고려한 프레임워크 → 다양한 요구사항을 손쉽게 추가하고 변경가능

OAuth를 통한 로그인 기능

최근 많은 서비스에서 로그인 기능을 id/passward 방식보다 구글, 페이스북, 네이버 등과같은 소셜 로그인 기능을 사용합니다

왜 많은 서비스에서 소셜 로그인?

직접 구현할 경우 아래를 전부 구현해야 하기 때문

  • 로그인 시 보안

  • 비밀번호 찾기

  • 회원가입 시 이메일 혹은 전화번호 인증

  • 비밀번호 변경

  • 회원정보 변경

이러한 기능들을 OAuth 로그인 구현시 다른 소셜에 맡기면 되니 서비스 개발에 부담을 줄여줍니다

Spring Security Oauth2 Client 라이브러리를 사용하여 구현합니다

  • 스프링 팀에서 기존 1.5에서 사용되던 spring-security-oauth 프로젝트는 유지 상태로 결정했으며 신규 기능은 추가하지 않고 버그 수정 정도의 기능만 추가될 예정, 신규 기능은 새 oauth2 라이브러리에서만 지원하겠다고 선언

  • 스프링 부트용 라이브러리 출시

  • 기존에 사용되던 방식은 확장 포인트가 적절하게 오픈되어 있지 않아 직접 상속하거나 오버라이딩 해야하고 신규 라이브러리의 경우 확장 포인트를 고려해서 설계된 설계

CommonOAuth2Provider 라는 enum이 새롭게 추가되어 구글, 깃허브, 페이스북, 옥타의 기본 설정값은 모두 여기서 제공합니다

이외에 다른 소셜 로그인을 추가한다면 직접 다 추가해 주어야 합니다


구글 서버스 등록

먼저 구글 서비스에 신규 서비스를 생성합니다

여기서 발급된 인증 정보를 통해서 로그인 기능과 소셜 서비스 기능을 사용할 수 있으니 무조건 발급받고 시작해야 합니다

console.cloud.google.com → 새 프로젝트

사이드바 → 사용자 인증정보

OAuth 클라이언트 ID

동의 화면 구성

승인된 리디렉션 URI

  • 서비스에서 파라미터로 인증 정보를 주었을때 인증이 성공하면 구글에서 리다이렉트할 URL 입니다

  • 스프링부트 2버전의 시큐리티에서는 기본적으로 {도메인}/login/oauth2/code/{소셜서비스코드} 로 리다이렉트 URL을 지원하고 있습니다

  • 사용자가 별도로 리다이렉트 URL을 지원하는 Controller 를 만들 필요가 없습니다. 시큐리티에서 이미 구현해 놓은 상태입니다

  • 개발 단계 이므로 localhost:8080 으로 합니다

  • AWS 서버에 배포하게 되면 localhost가 아닌 추가로 주소를 추가해야합니다

만들기를 누르면 클라이언트 ID와 클라이언트 보안 비밀 코드를 얻을 수 있습니다


OAuth 설정

scope = profile, email

  • 많은 예제에서는 이 scope를 별도로 등록하지 않고 있습니다

  • 기본값이 opened,profile,email 이기 때문입니다

  • 강제로 profile, email 를 등록한 이유는 opened 라는 scope 가 있으면 Open Id Provider 로 인식하기 때문입니다

  • 이렇게 되면 OpenId Provider 인 서비스(구글)와 그렇지 않은 서비스(네이버, 카카오)로 나눠서 각각 OAuth2Service를 만들어야 합니다

  • 하나의 OAuth2Service로 사용하기 위해 일부러 opened scope를 빼고 등록합니다

부트에서는 properties 의 이름을 application-xxx.properties 로 만들게 되면 xxx라는 이름의 profile 이 생성되어 이를 통해 관리 할 수 있습니다. 즉, profile = xxx 라는 식으로 호출하면 해당 properties의 설정들을 가져올 수 있습니다.

application.properties 에 다음 코드를 추가합니다

이를 통해 profile 에 oauth를 추가합니다


.gitignore 를 통한 보안관련 커밋 피하기

구글 로그인을 위한 클라이언트 ID와 클라이언트 보안 비밀은 보안이 중요한 정보들입니다.

이들이 외부에 노출되지 않도록 ignore 합니다.

application-auth.properties 를 gitignore에 추가합니다

만약 gitignore 에 추가하였는데도 적용되지 않았다면 git 의 캐시 문제 때문입니다

해결법

git rm -r --cached .

git add .

git commit -m "fixed untracked files"

위 명령어를 통하여 캐시를 모두 삭제후 다시 add 하면 해결


스프링 시큐리티 설정

build.gradle 에 스프링 시큐리티 관련 의존성 하나를 추가합니다

    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client:2.7.2'

OAuth 라이브러리를 이용한 소셜 로그인 설정 코드

스프링 버전이 업데이트 됨에 따라 WebSecurityConfigurerAdapter와 그 외 몇 가지들이 Deprecated 됐습니다.
스프링에서는 다른 방식으로 시큐리티 설정을 권장하고 있는 듯 해보였습니다.

기존

@RequiredArgsConstructor
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final CustomOAuth2UserService customOAuth2UserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .headers().frameOptions().disable()
                    .and()
                        .authorizeRequests()
                        .antMatchers("/","/css/**","/images/**",
                                "/js/**","h2-console/**").permitAll()
                        .antMatchers("/api/v1/**").hasRole(Role.USER.name())
                        .anyRequest().authenticated()
                    .and()
                        .logout()
                            .logoutSuccessUrl("/")
                    .and()
                        .oauth2Login()
                        .userInfoEndpoint()
                        .userService(customOAuth2UserService);
    }
}

보시다시피 기존에는 WebSecurityConfigurerAdapter를 상속받아 설정을 오버라이딩 하는 방식이였는데 이제는 오버라이딩 하지 않고 모두 Bean으로 등록을 합니다
Security Config 가 void 에서 바뀌었기 때문에 마지막에 build 를 추가해줍니다

@RequiredArgsConstructor
@EnableWebSecurity
public class SecurityConfig{
    private final CustomOAuth2UserServiceImpl customOAuth2UserServiceImpl;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        http
                .csrf().disable()
                .headers().frameOptions().disable()
                .and()
                .authorizeRequests()
                .antMatchers("/","/css/**","/images/**",
                        "/js/**","h2-console/**").permitAll()
                .antMatchers("/api/v1/**").hasRole(Role.USER.name())
                .anyRequest().authenticated()
                .and()
                .logout()
                .logoutSuccessUrl("/")
                .and()
                .oauth2Login()
                .userInfoEndpoint()
                .userService(customOAuth2UserServiceImpl);
        return http.build();
    }
}

@EnableWebSecurity

  • Spring Security 설정들을 활성화시켜 줍니다

csrf().disable().headers().frameOptions().disable()

  • h2-console 화면을 사용하기 위해 해당 옵션들을 disable합니다

authorizeRequests

  • URL 별 권한 관리를 설정하는 옵션의 시작점입니다

  • authorizeRequests 가 선언되어야만 antMatchers 옵션을 사용할 수 있습니다

antMatchers

  • 권한 관리 대상을 지정하는 옵션입니다

  • URL, HTTP 메소드별로 관리가 가능합니다

  • “/“ 등 지정된 URL들은 permitAll() 옵션을 통해 전체 열람 권한을 주었습니다

  • “/api/v1/**” 주소를 가진 API는 USER 권한을 가진 사람만 가능하도록 했습니다

anyRequest

  • 설정된 값들 이외 나머지 URL들을 나타냅니다

  • 여기서는 authenticated()을 추가하여 나머지 URL들은 모두 인증된 사용자들에게만 허용하게 합니다

  • 인증된 사용자 즉, 로그인한 사용자들을 이야기합니다

logout().logoutSuccessUrl(“/“)

  • 로그아웃 기능에 대한 여러 설정의 진입점입니다

  • 로그아웃 성공 시 / 주소로 이동합니다

oauth2Login

  • OAuth2 로그인 기능에 대한 여러 설정의 진입점입니다

userInfoEndpoint

  • OAuth2 로그인 성공 이후 사용자 정보를 가져올 때의 설정들을 담당합니다

userService

  • 소셜 로그인 성공 시 후속 조치를 진행할 UserService 인터페이스의 구현체를 등록합니다 (위 프로젝트의 경우 Service의 구현체가 Impl기 때문에 Impl로 작성합니다)

  • 리소스 서버에서 사용자 정보를 가져온 상태에서 추가로 진행하고자 하는 기능을 명시할 수 있습니다


구현하기

1. 가장 먼저 주체가 되는 엔티티를 생성합니다 (유저 User)

@Getter
@NoArgsConstructor
@Entity
public class User extends BaseTimeEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String email;

    @Column
    private String picture;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private Role role;

    @Builder
    public User(String name, String email, String picture, Role role) {
        this.name = name;
        this.email = email;
        this.picture = picture;
        this.role = role;
    }

    public User update(String name, String picture){
        this.name = name;
        this.picture = picture;
        return this;
    }

    public String getRoleKey(){
        return this.role.getKey();
    }
}

@Enumerated(EnumType.STRING)

  • JPA 로 데이터베이스로 저장할 때 Enum 값을 어떤 형태로 저장할 지를 결정합니다

  • 기본적으로는 int로 된 숫자가 저장됩니다

  • 숫자로 저장되면 데이터베이스로 확인할 때 그 값이 무슨 코드를 의미하는지 알 수가 없습니다

  • 그래서 문자열 (EnumType.STRING)로 저장될 수 있도록 선언합니다

@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseTimeEntity {

    @CreatedDate
    private LocalDateTime createdDate;

    @LastModifiedDate
    private LocalDateTime modifiedDate;
}
  • 유저의 작성일과 수정일을 자동으로 업로드 하도록 하기 위한 엔티티를 생성
    • 유저 클래스 뿐만아니라 다른 엔티티에서도 sysregdate 와 같이 생성일시, modDate의 경우 수정일시를 전역에서 사용할 수 있도록 생성해줍니다
    • @MappedSuperclass : JPA Entity 클래스들이 BaseTimeEntity를 상속할 경우 createdDate, modifiedDate 도 칼럼으로 인식되도록 합니다
    • @EntityListeners(AuditingEntityListener.class) : BaseTimeEntity 클래스에 Auditing 기능을 포함시킨다
    • @CreatedDate : 엔티티가 생성되어 저장될 때 시간이 자동 저장됩니다
    • @LastModifiedDate : 조회한 엔티티의 값을 변경할 때 시간이 자동 저장됩니다
@Getter
@RequiredArgsConstructor
public enum Role {

    GUEST("ROLE_GUEST", "손님"),
    USER("ROLE_USER","일반사용자");

    private final String key;
    private final String title;
}

각 사용자의 권한을 관리할 Enum 클래스 Role 을 생성합니다
스프링 시큐리티에서는 권한 코드에 항상 ROLE이 앞에 있어야만 합니다.
그래서 키 값을 지정할때
를 추가한것 입니다

2. User 의 CRUD를 책임질 UserRepository

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

findByEmail

  • 소셜 로그인으로 반환되는 값 중 email을 통해 이미 생성된 사용자인지 처음 가입하는 사용자인지 판단하기 위한 메소드입니다

3. 구글 로그인 이후 가져온 사용자의 정보들을 기반으로 가입 및 정보수정, 세션 저장 등의 기능을 지원

@RequiredArgsConstructor
@Service
public class CustomOAuth2UserServiceImpl implements CustomOAuth2UserService {
    private final UserRepository userRepository;
    private final HttpSession httpSession;

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) {
        OAuth2UserService<OAuth2UserRequest,OAuth2User> delegate
                = new DefaultOAuth2UserService();
        OAuth2User oAuth2User = delegate.loadUser(userRequest);

        String registrationId = userRequest.
                getClientRegistration().getRegistrationId();
        String userNameAttributeName = userRequest.
                getClientRegistration().getProviderDetails()
                .getUserInfoEndpoint()
                .getUserNameAttributeName();

        OAuthAttributes attributes = OAuthAttributes.
                of(registrationId,userNameAttributeName,
                        oAuth2User.getAttributes());

        User user = saveOrUpdate(attributes);
        httpSession.setAttribute("user", new SessionUser(user));

        return new DefaultOAuth2User(
                Collections.singleton(new
                        SimpleGrantedAuthority(user.getRoleKey())),
                attributes.getAttributes(),
                attributes.getNameAttributeKey());

    }

    @Override
    public User saveOrUpdate(OAuthAttributes attributes) {
        User user = userRepository.findByEmail(attributes.getEmail())
                .map(entity -> entity.update(attributes.getName(),
                        attributes.getPicture()))
                .orElse(attributes.toEntity());

        return userRepository.save(user);
    }
}

registrationId

  • 현재 로그인 진행중인 서비스를 구분하는 코드입니다

  • 지금은 구글만 사용하는 불필요한 값이지만, 이후 네이버 로그인 연동 시에 네이버 로그인인지, 구글 로그인인지 구분하기 위해 사용합니다

userNameAttributeName

  • OAuth2 로그인 진행 시 키가 되는 필드값을 이야기 합니다. PK와 같은 의미입니다

  • 구글의 경우 기본적으로 코드를 지원하지만, 네이버 카카오 등은 기본 지원하지 않습니다. 구글의 기본 코드는 “sub”입니다

  • 이후 네이버 로그인과 구글 로그인을 동시 지원할 때 사용됩니다

OAuthAttributes

  • OAuth2UserService를 통해 가져온 OAuth2User 의 attribute 를 담을 클래스입니다

  • 이후 네이버 등 다른 소셜 로그인도 이 클래스를 사용합니다

SessionUser

  • 세션에 사용자 정보를 저장하기 위한 Dto 클래스 입니다
@Getter
public class SessionUser implements Serializable {
    private String name;
    private String email;
    private String picture;

    public SessionUser(User user){
        this.name = user.getName();
        this.email = user.getEmail();
        this.picture = user.getPicture();
    }
}

"왜 User 로 관리하지 않고 SessionUser 로 따로 관리?"
만약 User 클래스를 그대로 상요했다면 다음과 같은 에러가 발생합니다
Failed to convert from type [java.lang.Object ] to type [byte[]] for value ‘springbok.domain.user.User@4a43d6’
세션에 저장하기 위해 User 클래스를 세션에 저장하려고 하니 User 클래스에 직렬화를 구현하지 않았다는 의미의 에러입니다
그렇다해도 User 클래스에 직렬화 코드를 넣어 해결하려 하면 안됩니다. User 클래스가 엔티티이기 때문에 언제 다른 엔티티와 다른 관계가 형성될지 모르는 상태에서 직렬화 코드를 넣어버리면 관계가 형성될때마다 수정해주어야 합니다.

구글 사용자 정보가 업데이트 되었을 때를 대비하여 update 기능도 같이 구현되었습니다. 사용자의 이름이나 프로필이 변경되면 User 엔티티에도 반영됩니다

Flow:
userRequest 를 받음 → 디폴트서비스를 생성 → 서비스에서 유저를 로드함 → 등록 id, attributeName을 request 를 통해 받아옴 → 이름, attribute 로 Attribute 를 만들어 줌 → 해당 Attribute 를 통해 유저 정보를 등록 → 세션에 user 라는 이름으로 저장 → 싱글톤 패턴으로 생성된 OAuthUser 반환

4. OAuthAttributes 클래스

@Getter
public class OAuthAttributes {
    private Map<String, Object> attributes;
    private String nameAttributeKey;
    private String name;
    private String email;
    private String picture;

    @Builder
    public OAuthAttributes(Map<String, Object> attributes, String nameAttributeKey, String name, String email, String picture) {
        this.attributes = attributes;
        this.nameAttributeKey = nameAttributeKey;
        this.name = name;
        this.email = email;
        this.picture = picture;
    }

    public static OAuthAttributes of(String registrationId,
                                     String userNameAttributeName,
                                     Map<String, Object> attributes){
        return ofGoogle(userNameAttributeName, attributes);
    }

    private static OAuthAttributes ofGoogle(String userNameAttributeName,
                                            Map<String,Object> attributes) {
        return OAuthAttributes.builder()
                .name((String) attributes.get("name"))
                .email((String) attributes.get("email"))
                .picture((String) attributes.get("picture"))
                .attributes(attributes)
                .nameAttributeKey(userNameAttributeName)
                .build();
    }

    public User toEntity(){
        return User.builder()
                .name(name)
                .email(email)
                .picture(picture)
                .role(Role.GUEST)
                .build();
    }
}

of()

  • OAuth2User 에서 반환하는 사용자 정보는 Map 이기 때문에 값 하나하나를 변환해야만 합니다

  • 유저이름, 소셜코드, request 를 통해 받아온 사용자 정보를 통해 OAuthAttributes 를 만들어 줍니다

toEntity()

  • User 엔티티를 생성합니다

  • OAuthAttributes 에서 엔티티를 생성하는 시점은 처음 가입할 때입니다

  • 가입할 때의 기본 권한을 GUEST로 주기 위해서 role 빌더값에는 Role.GUEST를 사용합니다

  • OAuthAttributes 클래스 생성이 끝났으면 같은 패키지에 SessionUser 클래스를 생성합니다

0개의 댓글