[스프링] 스프링 부트와 AWS로 혼자 구현하는 웹 서비스 - 스프링 시큐리티와 OAuth 2.0으로 로그인 기능 구현하기

June·2021년 10월 14일
1

스프링 시큐리티는 막강한 인증과 인가긴으을 가진 프레임워크다. 인터셉터, 필터 기반의 기능을 구현하는 것보다 스프링 시큐리티를 통해 구현하는 것을 적극적으로 권장하고 있다.

스프링 시큐리티와 스프링 시큐리티 OAuth2 클라이언트

  • 로그인 시 보안
  • 회원가입 시 이메일 혹은 전화번호 인증
  • 비밀번호 찾기
  • 비밀번호 변경
  • 회원정보 변경

OAuth 로그인 구현시 앞선 목록의 모든 것을 모두 구글, 페이스북, 네이버 등에 맡기면 되니 서비스 개발에 집중할 수 있다.

스프링 부트 1.5 vs 스프링 부트 2.0

스프링 부트 1.5에서 OAuth2 연동 방법이 2.0에서 크게 변경되었다. 하지만 인터넷 자료들을 보면 설정 방법에 크게 차이가 없는 경우가 자주 있다.

이는
spring-security-oauth2-autoconfigure 라이브러리 덕분이다.
이 라이브러리르 사용하면 1.5에서 쓰던 설정을 2.0에서 그대로 쓸 수 있다.

하지만 이 책에서는 스프링 부트 2 방식인 Spring Security Oauth 2 Client 라이브러를 사용한다.

  • 스프링 팀에서 기존 라이브러리는 유지 상태로 결정했으며, 신규 기능은 추가 없을 예정. 신규 기능은 새 oauth2 라이브러리만 지원하겠다고 선언.

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

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

구글 서비스 등록

먼저 구글 서비스에 신규 서비스를 생성한다. 여기서 발급된 인증 정보(clientId와 clientSecret)을 통해서 로그인 기능과 소셜 서비스 기능을 사용할 수 있으니 무조건 발급받고 시작해야 한다.

https://console.cloud.google.com/

Credentialn (사용자 인증 정보) 선택

동의 화면 구성

  • 앱 이름: 구글 로그인 시 사용자에게 노출될 애플리케이션 이름

  • 지원 이메일: 사용자 동의 화면에서 노출될 이메일 주소. 보통은 서비스의 help 주소를 사용하지만, 여기서는 독자의 이메일 주소를 사용한다.

  • Google API의 범위: 구글 서비스에서 사용할 범위 목록.

oAuth 클라이언트 ID 선택

승인된 리디렉션 URI

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

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

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

  • 현재는 개발 단계이므로 http://localhost:8080/login/oauth2/code/google로만 등록한다

  • AWS 서버에 배포하게되면 localhost 외에 추가로 주소 등록해야하며, 이는 나중에 진행한다.

application-oauth.properties

spring.security.oauth2.client.registration.google.client-id=클라이언트 ID
spring.security.oauth2.client.registration.google.client-secret=클라이언트 보안 비밀
spring.security.oauth2.client.registration.google.scope=profile, email
scope = profile, email
  • 많은 예제에서 이 scope를 별도로 등록하지 않고 있다.
  • 기본 값이 openid, profile, email이기 때문
  • 강제로 profile, email을 등록한 이유는 openid라는 scope가 있으면 Open Id Provider로 인식하기 때문
  • 이렇게 되면 OpenId Provider인 서비스(구글)와 그렇지 않은 서비스(네이버/카카오)로 나눠서 OAuth2Service를 만들어야 한다.
  • 하나의 OAuth2Service로 사용하기 위해 일부러 openid scope를 빼고 등록한다.

스프링 부트에서는 properties의 이름을 application-xxx.properties로 만들면 xxx라는 이름의 profile이 생성되어 이를 통해 관리할 수 있다. 즉, profie=xxx라는 식으로 호출하면 해당 properties의 설정들을 가져 올 수 있다. 여기에서는 스프링 부트의 기본 설정 파일인 application.properties에서 application-oauth.properties를 포함하도록 구성한다.

application.properties

spring.profiles.include=oauth

추가

.gitignore등록

application-oauth.properties

구글 로그인 연동하기

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();
    }
}
  1. @Enumerated(EnumType.String)
  • JPA로 데이터베이스를 저장할 때 Enum 값을 어떤 형태로 저장할지 결정한다.
  • 기본적으로 int로 된 숫자가 저장된다.
  • 숫자로 저장되면 데이터베이스로 확인했을 때, 그 값이 무슨 코드인지 알 수 없다.
  • 그래서 문자열 (EnumType.STRING)로 저장될 수 있도록 선언한다.

Role

@Getter
@RequiredArgsConstructor
public enum Role {

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

    private final String key;
    private final String title;
}

스프링 시큐리티에서는 권한 코드에 항상 ROLE_이 앞에 있어야 한다. 그래서 코드별 키 값을 ROLE_GUEST, ROLE_USER 등으로 지정한다.

UserRepository

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findByEmail(String email);
}
  1. findByEmail
    소셜 로그인으로 반환되는 값 중 email을 통해 이미 생성된 사용자인지 처음 가입하는 사용자인지 판단하기 위함이다.

스프링 시큐리티 설정

build.gradle

compile('org.springframework.boot:spring-boot-starter-oauth2-client')
  1. spring-boot-starter-oauth2-client
  • 소셜 로그인 등 클라이언트 입장에서 소셜 기능 구현시 필요한 의존성
  • spring-security-oauth2-client와 spring-security-oauth2-jose를 기본적으로 관리해준다.

시큐리티 관련 클래스는 모두 이곳에 담는다고 보면 된다.

SecurityConfig

package com.jojoldu.book.springboot.config.auth;

import com.jojoldu.book.springboot.domain.user.Role;
import lombok.RequiredArgsConstructor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@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/**", "/profile").permitAll()
                    .antMatchers("/api/v1/**").hasRole(Role.USER.name())
                    .anyRequest().authenticated()
                .and()
                    .logout()
                        .logoutSuccessUrl("/")
                .and()
                    .oauth2Login()
                        .userInfoEndpoint()
                .userService(customOAuth2UserService);
    }
}
  1. @EnableWebSecurity
    • Spring Security 설정들을 활성화 시켜준다.
  2. csrf().disable().headers().frameOptions().disable()
    • h2-console 화면을 사용하기 위해 해당 옵션들을 disable 한다.
  3. authorizeRequests
    • URL 별 권한 관리를 설정하는 옵션의 시작점이다.
    • authorizeRequests가 선언되어야만 anyMathcers 옵션을 사용할 수 있다.
  4. antMatchers
    • 권한 관리 대상을 지정하는 옵션이다
    • URL, HTTP 메소드별로 관리가 가능하다
    • "/"등 지정된 URL들은 permitAll() 옵션을 통해 전체 열람 권한을 주었다
    • /api/v1/**주소를 가진 API는 USER 권한을 가진 사람만 가능하도록 했다.
  5. anyRequest
    • 설정된 값들 이외 나머지 URL들을 나타낸다.
    • 여기서는 authenticated()을 추가하여 나머지 URL들은 모두 인증된 사용자들에게만 허용한다.
    • 인증된 사용자 즉, 로그인한 사용자들을 이야기 한다.
  6. logout().logoutSuccessUrl("/")
    • 로그아웃 기능에 대한 여러 설정의 진입점이다.
    • 로그아웃 성공 시 /주소로 이동한다.
  7. oauth2login
    • OAuth2 로그인 기능에 대한 여러 설정의 진입점이다
  8. userInfoEndpoint
    • OAuth2 로그인 성공 이후 사용자 정보를 가져올 때의 설정들을 담당한다
  9. userService
    • 소셜 로그인 성공 시 후속 조치를 진행할 UserService 인터페이스의 구현체를 등록한다.
    • 리소스 서버(즉, 소셜 서비스들)에서 사용자 정보를 가져온 상태에서 추가로 진행하고자 하는 기능을 명시할 수 있다.

아래 클래스에서 구글 로그인 후 가져온 사용자의 정보를 ㅣ반으로 가입 및, 정보수정, 세션 저장 등이 기능을 지원한다.

CustomOAuth2UserService

import com.jojoldu.book.springboot.config.auth.dto.OAuthAttributes;
import com.jojoldu.book.springboot.config.auth.dto.SessionUser;
import com.jojoldu.book.springboot.domain.user.User;
import com.jojoldu.book.springboot.domain.user.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
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 javax.servlet.http.HttpSession;
import java.util.Collections;

@RequiredArgsConstructor
@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
    private final UserRepository userRepository;
    private final HttpSession httpSession;

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2UserService 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());
    }


    private 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);
    }
}
  1. registrationId
    • 현재 로그인 진행 중인 서비스를 구분하는 코드이다
    • 지금은 구글만 사용하는 불필요한 값이지만, 이후 네이버 로그인 연동 시에 네이버 로그인인지, 구글 로그인인지 구분하기 위해 사용합니다.
  2. userNameAttributeName
    • OAuth2 로그인 진행 시 키가 되는 필드값을 이야기한다. Primary Key와 같은 의미이다.
    • 구글의 경우 기본적으로 코드를 지원하지만, 네이버 카카오 등은 기본 지원하지 않는다. 구글의 기본 코드는 "sub"이다.
    • 이후 네이버 로그인과 구글 로그인을 동시 지원할 때 사용된다.
  3. OAuthAttributes
    • OAuth2UserService를 통해 가져온 OAuth2User의 attribute를 담을 클래스이다.
    • 이후 네이버 등 다른 소셜 로그인도 이 클래스를 사용한다.
    • 바로 아래에서 이 클래스의 코드가 나오니 차례로 생성하면 된다.
  4. SessionUser
    • 세션에 사용자 정보를 저장하기 위한 DTo 클래스다
    • User 클래스를 쓰지 않고 새로 만들어서 쓰는지 뒤에 나온다.

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

OAuthAttributes

package com.jojoldu.book.springboot.config.auth.dto;

import com.jojoldu.book.springboot.domain.user.Role;
import com.jojoldu.book.springboot.domain.user.User;
import lombok.Builder;
import lombok.Getter;

import java.util.Map;

@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) {
        if("naver".equals(registrationId)) {
            return ofNaver("id", 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();
    }

    private static OAuthAttributes ofNaver(String userNameAttributeName, Map<String, Object> attributes) {
        Map<String, Object> response = (Map<String, Object>) attributes.get("response");

        return OAuthAttributes.builder()
                .name((String) response.get("name"))
                .email((String) response.get("email"))
                .picture((String) response.get("profile_image"))
                .attributes(response)
                .nameAttributeKey(userNameAttributeName)
                .build();
    }

    public User toEntity() {
        return User.builder()
                .name(name)
                .email(email)
                .picture(picture)
                .role(Role.GUEST)
                .build();
    }
}
  1. of()
    • OAuth2User에서 반환하는 사용자 정보는 Map이기 때문에 값 하나하나를 변환해야 한다.
  2. toEntity()
    • User 엔티티를 생성한다
    • OAuthAttributes에서 엔티티를 생성하는 시점은 처음 가입할 때다.
    • 가입할 때의 기본 권한을 GUEST로 주기 위해서 role 빌더 값에는 Role.GUEST를 사용한다.
    • OAuthAttributes 클래스 생성이 끝났으면 같은 패키지에 SessionUser 클래스를 생성한다.

SessionUser

package com.jojoldu.book.springboot.config.auth.dto;

import com.jojoldu.book.springboot.domain.user.User;
import lombok.Getter;

import java.io.Serializable;

@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();
    }
}

SessionUser에는 인증된 사용자 정보만 필요하다. 그외 필요한 정보가 없으니 name, email, picture만 필드로 선언한다.

왜 User 클래스를 사용하면 안되나?

에러가 발생하는데, User 클래스를 세션에 저장하려고 하니 User 클래스에 직렬화를 구현하지 않았다라는 의미의 에러다. 그렇다면 직렬화를 구현하면 될까? User 클래스는 엔티티이다. 엔티티 클래스는 언제 다른 엔티티와 관계가 형성될지 모른다. 성능 이슈, 부수 효과가 발생할 확률이 높다. 그래서 직렬화 기능을 가진 세션 Dto를 하나 추가로 만드는 것이 많은 도움이 된다.

index.mustache

{{>layout/header}}

<h1>스프링부트로 시작하는 웹 서비스 Ver.2</h1>
<div class="col-md-12">
    <!-- 로그인 기능 영역 -->
    <div class="row">
        <div class="col-md-6">
            <a href="/posts/save" role="button" class="btn btn-primary">글 등록</a>
            {{#userName}}
                Logged in as: <span id="user">{{userName}}</span>
                <a href="/logout" class="btn btn-info active" role="button">Logout</a>
            {{/userName}}
            {{^userName}}
                <a href="/oauth2/authorization/google" class="btn btn-success active" role="button">Google Login</a>
                <a href="/oauth2/authorization/naver" class="btn btn-secondary active" role="button">Naver Login</a>
            {{/userName}}
        </div>
    </div>
    <br>
    <!-- 목록 출력 영역 -->
    <table class="table table-horizontal table-bordered">
        <thead class="thead-strong">
        <tr>
            <th>게시글번호</th>
            <th>제목</th>
            <th>작성자</th>
            <th>최종수정일</th>
        </tr>
        </thead>
        <tbody id="tbody">
        {{#posts}}
            <tr>
                <td>{{id}}</td>
                <td><a href="/posts/update/{{id}}">{{title}}</a></td>
                <td>{{author}}</td>
                <td>{{modifiedDate}}</td>
            </tr>
        {{/posts}}
        </tbody>
    </table>
</div>

{{>layout/footer}}
  1. {{#userName}}

    • 머스테치는 다른 언어와 같은 if문 (if userName != null 등)을 제공하지 않습니다.
    • true/flase 여부만 판단할 뿐입니다.
    • 그래서 머스테치에서는 항상 최종값을 넘겨줘야 합니다.
    • 여기서도 역시 userName이 있다면 userName을 노출시키도록 구성했습니다.
  2. a href = "/logout"

    • 스프링 시큐리티에서 기본적으로 제공하는 로그아웃 URL입니다.
    • 즉, 개발자가 별도로 저 URL에 해당하는 컨트롤러를 만들 필요가 없습니다.
    • SecurityConfig 클래스에서 URL을 변경할 순 있지만 기본 URL을 사용해도 충분하니 여기선 그대로 사용한다.
  3. {{^userName}}

    • 머스테치에서 해당 값이 존재하지 않는 경우에는 ^를 사용한다.
    • 여기서는 userName이 없다면 로그인 버튼을 노출한다.
  4. a href="/oauth2/authorization/google"

    • 스프링 시큐리티에서 기본적으로 제공하는 URL이다.
    • 로그아웃 URL과 마찬가지로 개발자가 별도의 컨트롤러를 생성할 필요가 없다.

IndexController

@RequiredArgsConstructor
@Controller
public class IndexController {

    private final PostsService postsService;
    private final HttpSession httpSession;

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("posts", postsService.findAllDesc());

        SessionUser user = (SessionUser) httpSession.getAttribute("user");
        if (user != null) {
            model.addAttribute("userName", user.getName());
        }
        return "index";
    }

    ...
}
  1. (SessionUser)httpSession.getAttribute("user")
    • 앞서 작성된 CustomOAuth2UserService에서 로그인 성공 시 세션에 SessionUser를 저장하도록 구성했습니다.
    • 즉, 로그인 성공 시 httpSession.getAttribute("user")에서 값을 가져올 수 있다.
  2. if (user != null)
    • 세션에 저장된 값이 있을 때만 model에 userName으로 등록한다.
    • 세션에 저장된 값이 없으면 model엔 아무런 값이 없는 상태이니 로그인 버튼이 보인다.

어노테이션 기반으로 개선하기

SessionUser user = (SessionUser) httpSession.getAttribute("user");

세션 값을 가져오는 부분이 반복된다. 이 부분을 메소드 인자로 세션값을 받아 오게 변경해보자.

@LoginUser 애노테이션을 생성하자.

LoginUser

package com.jojoldu.book.springboot.config.auth;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginUser {
}
  1. @Target(ElementType.PARAMETER)
    • 이 어노테이션이 생성될 수 있는 위치를 지정한다.
    • PARAMETER로 지정했으니 메소드의 파라미터로 선언된 객체에서만 사용할 수 있다.
    • 이 외에도 클래스 선언문에 쓸 수 있는 TYPE 등이 있다.
  2. @interface
    • 이 파일을 어노테이션 클래스로 지정한다.
    • LoginUser라는 이름을 가진 어노테이션이 생성되었다고 보면 된다.

같은 위치에 LoginUserArgumentResolver를 생성한다. 이 것은 HandlerMethodArgumentResolver를 구현한 클래스다. 조건에 맞는 경우 메소드가 있다면 HandlerMethodArgumentResolver의 구현체가 지정한 값으로 해당 메소드의 파라미터로 넘길 수 있다.

LoginUserArgumentResolver

package com.jojoldu.book.springboot.config.auth;

import com.jojoldu.book.springboot.config.auth.dto.SessionUser;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpSession;

@RequiredArgsConstructor
@Component
public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver {

    private final HttpSession httpSession;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        boolean isLoginUserAnnotation = parameter.getParameterAnnotation(LoginUser.class) != null;
        boolean isUserClass = SessionUser.class.equals(parameter.getParameterType());
        return isLoginUserAnnotation && isUserClass;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        return httpSession.getAttribute("user");
    }
}
  1. supportsParamter()
    • 컨트롤러 메서드의 특정 파라미터를 지원하는지 판단한다.
    • 여기서는 파라미터에 @LoginUser 어노테이션이 붙어 있고, 파라미터 클래스 타입이 SessionUser.class인 경우 true 를 반환한다.
  2. resolveArgument()
    • 파라미터에 전달할 객체를 생성한다.
    • 여기서는 세션에서 객체를 가져온다.

LoginUserArgumentResolver스프링에서 인식될 수 있도록 WebMvcConfigurer에 추가한다.

WebConfig

package com.jojoldu.book.springboot.config;

import com.jojoldu.book.springboot.config.auth.LoginUserArgumentResolver;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@RequiredArgsConstructor
@Configuration
public class WebConfig implements WebMvcConfigurer {
    private final LoginUserArgumentResolver loginUserArgumentResolver;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(loginUserArgumentResolver);
    }
}

HandlerMethodArgumentResolver는 항상 WebMvcConfigurer
addArgumentResolvers()를 통해서 추가해야 한다.

IndexController에서 반복되는 부분 @LoginUser로 개선한다.

IndexController

@RequiredArgsConstructor
@Controller
public class IndexController {

    private final PostsService postsService;
    //private final HttpSession httpSession;

    @GetMapping("/")
    public String index(Model model, @LoginUser SessionUser user) {
        model.addAttribute("posts", postsService.findAllDesc());
        
        if (user != null) {
            model.addAttribute("userName", user.getName());
        }
        return "index";
    }

    ...
}
  1. @LoginUser SessionUser user
    • 기존에 ```(User) httpSession.getAttribute("user")로 가져오던 세션 정보 값이 개선되었다.
    • 이제는 어느 컨트롤러든지 @LoginUser만 사용하면 세션 정보를 가져올 수 있다.

세션 저장소로 데이터베이스 사용하기

지금 우리가 만든 서비스는 애플리케이션을 재실행하면 로그인이 풀린다. 왜 그럴까? 이는 세션이 내장 톰캣의 메모리에 저장되기 떄문이다. 기본적으로 세션은 실행되는 WAS의 메모리에서 저장되고 호출된다. 메모리에 저장되다 보니 내장 톰캣처럼 애플리케이션 실행 시 실행 되는 구조에선 항상 초기화된다.

즉, 배포할 때마다 톰캣이 재시작된다. 이 외에도 한가지 문제가 더 있다. 2대 이상의 서버에서 서비스하고 있다면 톰캣에서 세션 동기화 설정을 해야만 한다. 그래서 현업에서는 세션 저장소에대해 다음 3가지 중 하나를 선택한다.

  1. 톰캣 세션을 사용한다.

    • 일반적으로 변다른 설정을 하지 않을 때 기본 선택 값이다.
    • 이렇게 될 경우 톰캣(WAS)에 세션이 저장되기 때문에 2대 이상의 WAS가 구동되는 환경에서는 톰캣들 간의 세션 공유를 위한 추가 설정이 필요하다
  2. MySQL과 같은 데이터베이스를 세션 저장소로 사용한다.

    • 여러 WAS 간의 공용 세션을 사용할 수 있는 가장 쉬운 방법이다.
    • 많은 설정이 필요 없지만, 결국 로그인 요청마다 DB IO가 발생하여 성능상 이슈가 발생할 수 있다.
    • 보통 로그인 요청이 많은 백오피스, 사내 시스템 용도에서 사용한다.
  3. Redis, Memcached와 같은 메모리 DB를 세션 저장소로 사용한다.

    • B2C 서비스에서 가장 만힝 사용하는 방식이다.
    • 실제 서비스로 사용하기 위해서는 Embedded Redis와 같은 방식이 아닌 외부 메모리 서버가 필요하다.

여기서는 두 번째 방식은 데이터베이스를 세션 저장소로 사용하겠다. 선택한 이유는 설정이 간단하고 사용자가 많은 서비스가 아니며 비용 절감을 위해서다. 이후 AWS에서 이 서비스를 배포할 것을 생각하면 레디스와 같은 메모리 DB는 부담스럽다. 레디스와 같은 서비스(엘라스틱 캐시)에 별도로 사용료를 지불해야 하기 때문이다.

build.gradle

compile('org.springframework.session:spring-session-jdbc')

application.properties

spring.session.store-type=jdbc

h2-console을 보면 세션을 위한 테이블 2개(SPRING_SESSION, SPRING_SESSION_ATTRIBUTES)가 생성된 것을 볼 수 있다. JPA로 인해 세션 테이블이 자동 생성되었기 때문에 별도로 해야할 일이 없다.

지금은 기존과 동일하게 스프링을 재시작하면 세션이 풀린다. H2도 재시작되기 때문이다.. 이후 AWS로 배포하게되면 AWS의 데이터베이스은 RDS를 사용하게 되니 이때부터 세션이 안 풀린다.

네이버 로그인

https://developers.naver.com/apps/#/wizard/register

해당 키값들을 application-oauth.properties에 등록한다. 네이버에서는 스프링 시큐리티를 공식지원하지 않기 때문에 그동안 CommonOAuth2Provider에서 해주던 값들도 전부 수동으로 입력한다.

application-oauth.properties

# registration
spring.security.oauth2.client.registration.naver.client-id=네이버클라이언트ID
spring.security.oauth2.client.registration.naver.client-secret=네이버클라이언트시크릿
spring.security.oauth2.client.registration.naver.redirect-uri={baseUrl}/{action}/oauth2/code/{registrationId}
spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.naver.scope=name,email,profile_image
spring.security.oauth2.client.registration.naver.client-name=Naver

# 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

맨 마지막에 user-name-attribute=response
- 기준이 되는 user_name의 이름을 네이버에서는 response로 해야한다는 뜻이다.
- 이는 네이버에서 제공하는 JSON형태 때문이다

스프링 시큐리티에선 하위 필드를 명시할 수 없다. 최상위 필드들만 user_name으로 지정가능하다. 네이버 응답값 최상위 필드는 resultCode, message, response이다.

스프링 시큐리티 설정 등록

OAuthAttributes에 다음과 같이 네이버인지 판단하는 코드와 네이버 생성자만 추가하면 된다.

OauthAttributes

@Getter
public class OAuthAttributes {
    ...

    public static OAuthAttributes of(String registrationId, String userNameAttributeName, Map<String, Object> attributes) {
        if("naver".equals(registrationId)) {
            return ofNaver("id", attributes);
        }

        return ofGoogle(userNameAttributeName, attributes);
    }

    ...

    private static OAuthAttributes ofNaver(String userNameAttributeName, Map<String, Object> attributes) {
        Map<String, Object> response = (Map<String, Object>) attributes.get("response");

        return OAuthAttributes.builder()
                .name((String) response.get("name"))
                .email((String) response.get("email"))
                .picture((String) response.get("profile_image"))
                .attributes(response)
                .nameAttributeKey(userNameAttributeName)
                .build();
    }

    ...
}

index.mustache

            {{^userName}}
	...
                <a href="/oauth2/authorization/naver" class="btn btn-secondary active" role="button">Naver Login</a>
            {{/userName}}
  1. /oauth2/authorization/naver
    • 네이버 로그인 URL은 application-oauth.properties에 등록한 redirect-uri 값에 맞춰 자동으로 등록된다.
    • /oauth2/authorization/까지는 고정이고 마지막 Path만 각 소셜 로그인 코드를 사용하면 된다.
    • 여기서는 naver가 마지막 Path가 된다.

기존 테스트에 시큐리티 적용하기

시큐리티 옵션이 활성화되면 인증된 사용자만 API를 호출할 수 있다. 기존의 API 테스트 코드들이 모두 인증에 대한 권한을 받지 못하였으므로, 테스트 코드마다 인증한 사용자가 호출한 것처럼 작동하도록 수정하겠다.

No qualifying bean of type 'com.jojoldu.book.springboot.config.auth.CustomOAuth2UserService' available:

오류가 발생한다.

이는 src/main환경과 src/test환경 차이 때문이다. 둘은 본인만의 환경 구성을 가진다. 다만 src/main/resources/application.properties가 테스트 코드를 수행할 때도 적용되는 이유는 test에 application.properties가 없으면 main의 설정을 그대로 가져오기 때문이다. 다만, 자동으로 가져오는 옵션의 범위는 application.properties까지다. 즉, application-oauth.propertiestest에 파일이 없다고 가져오는 파일은 아니다.

가짜 설정값을 만들자.

test/resources/application.properties

spring.jpa.show_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.h2.console.enabled=true
spring.session.store-type=jdbc

# Test OAuth

spring.security.oauth2.client.registration.google.client-id=test
spring.security.oauth2.client.registration.google.client-secret=test
spring.security.oauth2.client.registration.google.scope=profile,email

문제 2. 302 Status Code

이는 스프링 시큐리티 설정 때문에 인증되지 않은 사용자의 요청은 이동시키기 때문이다. 이런 API 요청은 임읠로 인증된 사용자를 추가하여 API만 테스트해볼 수 있게 하겠다.

스프링 시큐리티 테스트를 위한 여러 도구를 지원하는 spring-security-testbuild.gradle에 추가한다.

build.gradle

testCompile('org.springframework.security:spring-security-test')

PostsApiControllerTest

    @Test
    @WithMockUser(roles = "USER")
    public void Posts_등록된다() throws Exception {
    ...
    
    @Test
    @WithMockUser(roles = "USER")
    public void Posts_수정된다() throws Exception {
    ...
  1. @WithMockUser(roles="USER")
    • 인증된 모의 사용자를 만들어서 사용한다.
    • roles에 권한을 추가할 수 있다.
    • 즉, ROLE_USER 권한을 가진 사용자가 API를 요청하는 것과 동일한 효과를 가진다.

아직 테스트가 안되는데, @WithMockUserMockMvc에서만 작동하기 때문이다. @SpringBootTest에서 MockMVC를 사용하는 방법이 필요하다.

PostApiController

package com.jojoldu.book.springboot.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jojoldu.book.springboot.domain.posts.Posts;
import com.jojoldu.book.springboot.domain.posts.PostsRepository;
import com.jojoldu.book.springboot.web.dto.PostsSaveRequestDto;
import com.jojoldu.book.springboot.web.dto.PostsUpdateRequestDto;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PostsApiControllerTest {
    ...

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;
    
    @Before
    public void setup() {
        mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity())
                .build();
    }

    @Test
    @WithMockUser(roles = "USER")
    public void Posts_등록된다() throws Exception {
        ...

        // when
        ResponseEntity<Long> responseEntity = restTemplate.postForEntity(url, requestDto, Long.class);

        //then
        Assertions.assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
        Assertions.assertThat(responseEntity.getBody()).isGreaterThan(0L);

        List<Posts> all = postsRepository.findAll();
        Assertions.assertThat(all.get(0).getTitle()).isEqualTo(title);
        Assertions.assertThat(all.get(0).getContent()).isEqualTo(content);
    }

    @Test
    @WithMockUser(roles = "USER")
    public void Posts_수정된다() throws Exception {
        ...

        // when
        ResponseEntity<Long> responseEntity = restTemplate.
                exchange(url, HttpMethod.PUT, requestEntity, Long.class);

        // then
        Assertions.assertThat(responseEntity.getStatusCode())
                .isEqualTo(HttpStatus.OK);

        Assertions.assertThat(responseEntity.getBody()).isGreaterThan(0L);

        List<Posts> all = postsRepository.findAll();

        Assertions.assertThat(all.get(0).getTitle()).
                isEqualTo(expectedTitle);

        Assertions.assertThat(all.get(0).getContent()).
                isEqualTo(expectedContent);
    }
}
  1. mvc.perform
    • 생성된 MockMvc를 통해 API를 테스트한다.
    • 본문(Body) 영역은 문자열로 표현하기 위해 ObjectMapper를 통해 문자열 JSON으로 변환한다.

문제 3 @WebMvcTest에서 CustomOAuth2UserService을 찾을 수 없음
HelloControllerTest@WebMvcTest를 사용한다. @WebMvcTest는 CustomOAuth2UserService를 스캔하지 않기 때문에 문제가 발생한다.

@WebMvcTestWebSecurityConfigurerAdapter, WebMvcConfigurer를 비로한 @ControllerAdvice, @Controller를 읽는다. 즉, @Repository, @Service, @Component는 스캔 대상이 아니다. 그러니 SecurityConfig는 읽었지만, SecurityConfig를 생성하기 위해 필요한 CustomOAuth2UserService는 읽을 수가 없어 에러가 발생한 것이다. 그래서 이 문제를 해결 하기 위해 **스캔 대상에서 SecurityConfig를 제거한다

HelloController

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloController.class, 
    excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class)
    })
public class HelloControllerTest {
    ...
    @WithMockUser(roles = "USER")
    @Test
    public void hello가_리턴된다() throws Exception {
        ...
    }
    
    @WithMockUser(roles = "USER")
    @Test
    public void helloDto가_리턴된다() throws Exception {
        ...
    }
}
At least on JPA metamodel must be present!

여전히 에러가 발생한다.

@EnableJpaAuditing으로 인해 발생한다. @EnableJpaAuditing를 사용하기 위해서는 최소 하나의 @Entity 클래스가 필요하다. @EnableJpaAuditing@SpringBootApplication과 함께 있다보니 @WebMvcTeest에서도 스캔하게 되었다. 그래서 분리하면 된다.

Application

//@EnableJpaAuditing
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

JpaConfig

package com.jojoldu.book.springboot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@Configuration
@EnableJpaAuditing // JPA Auditing 활성화
public class JpaConfig {
}

0개의 댓글