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

  • 반복되는 같은 코드 해결하기
    • 커스텀 어노테이션(@LoginUser) 만들기
    • ArgumentResolver

커스텀 어노테이션 생성

  • 세션 처리를 위한 @LoginUser 어노테이션 생성
    1. @Target(ElementType.PARAMETER)
      • 어노테이션이 생성될 수 있는 위치를 지정
      • PARAMETER로 지정하므로써 메서드의 파라미터로 선언된 객체에서만 사용될 수 있다.
      • 이 외에도 클래스 선언시 사용할 수 있는 TYPE 등이 있다.
    2. @Interface
      • 해당 파일을 어노테이션 클래스로 지정
      • LoginUser라는 이름을 가진 어노테이션을 사용할 수 있다.
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginUser {
}

LoginUserArgumentResolver

  • ArgumentResolver 생성

    • HandlerMethodArgumentResolver 인터페이스를 구현한 클래스
    • 조건에 맞는 경우 메서드가 있다면, HandlerMethodArguementResolver의 구현체가 지정한 값으로 해당 메서드의 파리미터로 넘길 수 있다.
    1. supportParameter()
      • 컨트롤러 메서드의 특정 파라미터를 지원하는지 판단
      • 파라미터에 @LoginUser 어노테이션이 붙어있고, 파라미터 클래스 타입이 SessionUser.class인 경우 true를 반환
    2. resolveArgument()
      • 파라미터에 전달할 객체를 생성
      • 해당 코드에서는 세션에서 객체를 가져온다.
@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");
    }
}

ArgumentResolver 설정

  • WebConfig
    • 스프링에서 LoginUserArgumentResolver를 인식할 수 있도록 WebMvcConfigurer를 구현한 WebConfig 클래스에 설정한다.
    • WebMvcConfigurer의 addArgumentResolvers()를 추가한다.
    • 다른 HandlerMethodArgumentResolver가 필요한 경우 같은 방식으로 추가한다.
@RequiredArgsConstructor
@Configuration
public class WebConfig implements WebMvcConfigurer {
    private final LoginUserArgumentResolver loginUserArgumentResolver;

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

Controller 수정

  • 세션을 사용하는 부분 수정

    • @LoginUser를 파라미터로 받아 사용할 수 있도록 수정
    1. @LoginUser SessionUser user
      • 기존 (SessionUser) httpSession.getAttribute("user")로 가져오던 세션 정보 값을 개선
      • 다른 컨트롤러에서 세션이 필요한 경우 @LoginUser를 사용하여 세션 정보를 가져올 수 있다.
@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";
    }

    @GetMapping("/posts/save")
    public String postsSave() {
        return "posts-save";
    }

    @GetMapping("/posts/update/{id}")
    public String postsUpdate(@PathVariable Long id, Model model) {
        PostsResponseDto dto = postsService.findById(id);
        model.addAttribute("post", dto);
        return "posts-update";
    }
}

어노테이션 기반으로 변경하여 다시 세션 체크

  • 글 작성 테스트

  • 글 등록 확인

로그인 테스트

  • 화면에 로그인 버튼 추가하기 & 로그인 성공 시 사용자명 나타내기
  • 컨트롤러에서 사용자명 저장하여 화면으로 전달하기
  • DB 테이블 확인하기
  • 글쓰기로 권한 관리 확인

FrontEnd

index.mustache

  • 로그인 버튼

    1. {{#userName}}

      • mustache는 다른 언어와 같은 if문을 제공하지 않는다.
      • true / false 여부만 판단
      • mustache에 항상 최종 값을 넘겨줘야 한다.
      • userName이 있다면 userName을 노출하도록 구성
    2. a href="/logout"

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

      • mustache에서 해당 값이 존재하지 않는 경우 ^를 사용
      • userName이 없다면 로그인 버튼을 노출하도록 구성
    4. a href="/oauth2/authorization/google"

      • 스프링 시큐리티에서 기본적으로 제공하는 로그인 URL
      • 로그아웃 URL과 마찬가지로 개발자가 별도의 컨트롤러를 생성할 필요가 없다.
    <h1>스프링 부트로 시작하는 웹 서비스 No. 3</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>
        <!-- -->
    </div>

BackEnd

IndexController

  • 컨트롤러 수정
    1. (SessionUser) httpSession.getAttribute("user")
      • CustomOAuth2UserService에서 로그인 성공 시 세션에 SessionUser를 저장하도록 구성
      • 로그인 성공 시 httpSession.getAttribute("user")에서 값을 가져올 수 있다.
    2. if (user != null)
      • 세션에 저장된 값이 있을 때만 model에 userName으로 등록
      • 세션에 저장된 값이 있으면 model엔 아무런 값이 없는 상태이니 로그인 버튼이 보이게 된다.
@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";
    }

    // save, update
}

OAuth2 Google 로그인 및 권한 테스트

화면 수정 확인

화면 수정 로그인 버튼 확인

OAuth2 Google 연동 확인

OAuth2 확인

로그인 확인

로그인 확인

DB 내에 로그인 확인

OAuth2 Google Login 확인

로그인 유저 Role 수정

로그인 유저 Role 'User'로 수정

User Role 'USER'로 변경 후 글 등록 테스트 확인

글 등록 확인

OAuth2 Google Login

스프링 시큐리티 설정

  • build.gradle에 스프링 시큐리티 관련 의존성 추가
    1. spring-boot-starter-oauth2-client
      • 소셜 로그인 등 클라이언트 입장에서 소셜 기능 구현 시 필요한 의존성
      • spring-boot-oauth2-client와 spring-security-oauth2-jose를 기본으로 관리
dependencies {
    // ...
    compile('org.springframework.boot:spring-boot-starter-oauth2-client')

    // test
}

사용자 관련 클래스 생성

  • Dto 분류
    • 권한
    • 사용자 정보

사용자 권한(User Authrization)을 위한 Role 클래스 생성

  • Role 클래스
    • 각 사용자의 권한을 관리할 Enum 클래스
    • 스프링 시큐리티에서는 권한 코드에 항상 "ROLE_" 이 앞에 있어야 한다.
    • 코드별 키 값을 ROLE_GUEST, ROLE_USER 등으로 지정
@Getter
@RequiredArgsConstructor
public enum Role {

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

    private final String key;
    private final String title;
}

사용자 정보(User) 담당할 도메인 클래스 생성

  • User

    • @Enumerated(EnumType.STRING)

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

사용자관련 CRUD 작업할 UserRepository 생성

  • UserRepositry
    • findByEmail
      • 소셜 로그인으로 반환되는 값 중 email을 통해 이미 생성된 사용자인지 처음 가입하는 사용자인지 판단하기 위한 메서드
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

시큐리티 관련 패키지 및 클래스 생성

  • config.auth 패키지 생성

    • 시큐리티 관련 클래스 관리

    • SessionUser

    • OAuthAttributes

    • CustomOAuth2UserService

    • SecurityConfig

SessionUser 생성

  • SessionUser

    • 인증된 사용자 정보를 저장하는 클래스
    • User클래스 내에 세션 정보를 가질 수 없는 이유
  • SessionUser 클래스의 이유

    • User 클래스에 Session을 저장하려는 경우, User 클래스에 직렬화를 하지 않았기 때문에 오류가 발생한다.
    • User 클래스에 직렬화 코드를 넣는다면 ?
      • User 클래스는 Entity 클래스이기 때문에 문제가 발생할 가능성이 높다.
      • Entity 클래스는 언제 다른 엔티티와 관계가 형성될 지 모르기 때문이다.
      • @OneToMany, @ManyToMany 등 자식 엔티티를 갖고 있다면 직렬화 대상에 자식들까지 포함되니 성능 이슈, 부수 효과가 발생할 확률이 높다.
      • 직렬화 기능을 가진 세션 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();
    }
}

OAuthAttributes 생성

  • OAuthAttributes 클래스
    1. of()
      • OAuth2User에서 반환하는 사용자 정보는 Map이기 때문에 값 하나하나를 변환해야 한다.
    2. toEntity()
      • User 엔티티를 생성
      • OAuthAttributes에서 엔티티를 생성하는 시점은 처음 가입할 때이다.
      • 가입할 때의 기본 권한을 GUEST로 주기 위해서 role 빌더 값에는 Role.GUEST를 사용
@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);
    }

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

CustomOAuth2UserService 생성

  • CustomOAuth2UserService
    1. registrationId
      • 현재 로그인 진행 중인 서비스를 구분하는 코드
      • 추후 네이버 로그인 연동 시에 네이버 로그인인지, 구글 로그인인지 구분하기 위한 값
    2. userNameAttributeName
      • OAuth2 로그인 진행 시 키가 되는 필드값을 이야기한다.
      • Primary Key와 같은 의미
      • 구글의 경우 기본적으로 코드를 지원하지만, 네이버 카카오 등은 기본 지원하지 않는다.
      • 구글의 기본 코드는 'sub'
      • 이후 네이버 로그인과 구글 로그인을 동시 지원할 때 사용
    3. OAuthAttributes
      • OAuth2UserService를 통해 가져온 OAuth2User의 attribute를 담을 클래스
      • 이후 네이버 등 다른 소셜 로그인도 이 클래스를 사용
    4. SessionUser
      • 세션에 사용자 정보를 저장하기 위한 Dto 클래스
@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);
    }
}

Security Config 클래스 생성

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

스프링 시큐리티(Spring Security)

  • 인증(Authentication)와 인가(Authorization) 기능을 가진 프레임워크
  • 스프링 기반의 어플리케이션에서는 보안을 위한 표준
  • 인터셉터, 필터 기반의 보안 기능을 구현하는 것보다 스프링 시큐리티를 통해 구현하는 것을 권장

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

  • 직접 구현하는 경우 개발해야할 기능
    • 로그인 시 보안
    • 비밀번호 찾기
    • 비밀번호 변경
    • 회원가입 시 이메일 혹은 전화번호 인증
    • 회원정보 변경
  • OAuth 로그인 구현 시 위 목록들을 모두 구글, 페이스북, 네이버 등에 맡겨 서비스 개발에 집중

Spring Boot 2.0의 OAuth 2.0 설정 방법

  • OAuth2 설정

    • spring-security-oauth2-autoconfigure 라이브러리는 Spring Boot2에서도 1.5에서 쓰던 설정을 사용할 수 있다.
      • 기존에 사용되던 방식은 확장 포인트가 적절하게 오픈되어있지 않아 직접 상속하거나 오버라이딩 해야 하고, 신규 라이브러리의 경우 확장 포인트를 고려해서 설계된 상태
    • 여기서는 Spring Security Oauth2 Client 라이브러리 사용
      • 기존 1.5 에서 사용되던 spring-security-oauth 프로젝트는 신규 기능 없이 유지
      • 신규 기능은 새 oauth2 라이브러리에서만 지원
  • 스프링 부트용 라이브러리(starter) 출시

  • 스프링 부트2.0 security 설정 정보 확인 방법

    • spring-security-oauth2-autoconfigure 라이브러리 확인
    • application.properties 혹은 application.yaml 정보에 차이 비교

SpringBoot 1.5 버전 설정

google:  
  client:  
    clientId: 인증정보  
    clientSecret: 인증정보  
    accessTokenUrl: {url}  
    userAuthorizationUrl: {url}  
    clientAuthenticationScheme: form  
    scope: email, profile  
  resource:  
    userInfoUrl: {url}

SpringBoot 2.x 버전 설정

spring:  
  security:  
    oauth2:  
      client:  
        clientId: 인증정보  
        clientSecret: 인증정보

버전 차이

  • SpringBoot 1.5 vs 2.x
    • 1.5 방식에서는 url 주소를 모두 명시해야 하지만, 2.0 방식에서는 client 인증 정보만 입력하면 된다.
    • 1.5 버전에서 직접 입력했던 값들은 2.0버전으로 오면서 모두 emum으로 대체 되었다.
    • CommonOAuth2Provider에서 구글, 깃허브, 페이스북, 옥타(Okta)의 기본 설정 값을 제공한다.
    • 이외 다른 소셜 로그인(naver, kakao)을 추가한다면 직접 다 추가 해야 한다.
public enum CommonOAuth2Provider {

    GOOGLE {

        @Override
        public Builder getBuilder(String registrationId) {
            ClientRegistration.Builder builder = getBuilder(registrationId,
                    ClientAuthenticationMethod.BASIC, DEFAULT_REDIRECT_URL);
            builder.scope("openid", "profile", "email");
            builder.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth");
            builder.tokenUri("https://www.googleapis.com/oauth2/v4/token");
            builder.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs");
            builder.userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo");
            builder.userNameAttributeName(IdTokenClaimNames.SUB);
            builder.clientName("Google");
            return builder;
        }
    },
    // ... 
}

구글 서비스 등록

  • 구글 서비스 신규 서비스 생성
    • 발급된 인증 정보(clientId, clientSecret)을 통해 로그인 기능과 소셜 서비스 기능을 사용

Google Cloud Platform

  • 프로젝트 선택

구글 클라우드 플랫폼

  • 새 프로젝트

새 프로젝트

  • 프로젝트 서비스 명 입력

등록될 서비스의 이름 입력

  • API 및 서비스 카테고리 -> 사용자 인증 정보

API 및 서비스 -> 사용자 인증 정보

  • 사용자 인증 정보 만들기 -> OAuth 클라이언트 ID

OAuth 클라이언트 ID

  • 다시 OAuth 클라이언트 ID 만들기 페이지로 이동

동의 화면 구성

  • Type 선택 (외부 선택 밖에 안됨)

  • 어플리케이션 이름 작성, Google API 범위 확인
    • 어플리케이션 이름
      • 구글 로그인 시 사용자에게 노출될 어플리케이션 이름
    • 지원 이메일
      • 사용자 동의 화면에서 노출될 이메일 주소
    • Google API의 범위
      • 구글 서비스에서 사용할 범위 목록
      • 기본값은 email, profile, openId (다른 정보 사용시 추가 가능)

동의 화면 구성

  • OAuth 클라이언트 ID 페이지 이동

  • OAuth 클라이언트 ID 만들기 페이지 이동
    • 어플리케이션 유형 선택
    • 프젝트명 입력
    • [승인된 리다이렉션 URL] 추가
      • 스프링 부트 시큐리티에서 기본적으로 {domain}/login/oauth2/code/{소셜서비스코드}로 리다이렉트
      • 현재 소셜서비스코드는 'google'
      • 서비스에서 파라미터로 인증 정보를 주었을 때, 인증이 성공하면 구글에서 리다이렉트할 URL
      • 시큐리티에서 구현되어 있기 때문에, 사용자가 별도로 리다이렉트 URL을 지원하는 Controller를 만들 필요가 없다.
      • AWS 서버에 배포할 경우 localhost 외에 주소를 추가해야 한다.
      • 현재는 로컬에서 개발하기 때문에 http://localhost:8085/login/oauth2/code/google 등록

  • 완료 후 클라이언트 ID, 클라이언트 Secret 확인
    • 해당 값들을 프로젝트에 설정해야 한다.

  • OAuth 2.0 클라이언트 ID 생성 확인

  • 생성된 클라이언트 ID 접근 해보면 서비스에 클라이언트 ID, 클라이언트 Secret 생성된 것을 확인 가능

  • 프로젝트에 OAuth 설정 적용
    • resources 디렉토리에 application-oauth.properties 파일 생성

  • application-oauth.properties 파일 내에 구글 OAuth 설정
    • 클라이언트 ID 값 설정
    • 클라이언트 보안 값 설정
    • scope는 profile, email을 강제 설정
      • 기본값은 openId, profile, email 이다.
      • 하지만 openId를 그대로 설정하는 경우 Open Id Provider로 인식하게 된다.
      • 그리할 경우 OpenId Provider인 서비스(구글)와 그렇지 않은 서비스(Naver, Kakao 등) 나눠서 OAuth2Service를 만들어야 한다.
      • 하나의 OAuth2Sercice를 사용하기 위해 openId scope를 제외한다.
spring.security.oauth2.client.registration.google.client-id={clientId}
spring.security.oauth2.client.registration.google.client-secret={clientSecret}
spring.security.oauth2.client.registration.google.scope=profile,email
  • application.properties 파일에서 application-oauth.properties를 포함하도록 구성

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

spring.profiles.include=oauth

'Spring > SpringBoot' 카테고리의 다른 글

[SpringBoot] 로그인 & 포스팅 권한 테스트  (0) 2020.05.31
[SpringBoot] OAuth2 Google Login  (0) 2020.05.31
[SpringBoot] 게시글 삭제  (0) 2020.05.29
[SpringBoot] 게시글 수정  (0) 2020.05.29
[SpringBoot] 게시글 전체 조회  (0) 2020.05.29

게시글 삭제

  • 수정화면에 삭제 버튼 기능 추가

FrontEnd

posts-update.mustache

  • update
    • btn-delete
      • 삭제 버튼을 수정 완료 옆에 추가
      • id가 btn-delete인 버튼의 click 이벤트가 발생하는 경우 게시글 삭제 javaScript delete 함수 호출
{{>layout/header}}

    <h1>게시글 수정</h1>

    <div class="col-md-12">
        <div class="col-md-4">

            <!-- ... -->

            <a href="/" role="button" class="btn btn-secondary">취소</a>
            <button type="button" class="btn btn-primary" id="btn-update">수정 완료</button>
            <button type="button" class="btn btn-danger" id="btn-delete">삭제</button>
        </div>
    </div>

{{>layout/footer}}

index.js

  • index
    • btn-delete 버튼 이벤트 등록
    • delete 함수 호출 시 /api/v1/posts/{id} URL 로 DELETE Method 방식으로 호출하여 게시글을 삭제 요청
var main = {
    init : function () {
        var _this = this;
        $('#btn-save').on('click', function () { _this.save(); });
        $('#btn-update').on('click', function () { _this.update(); });
        $('#btn-delete').on('click', function () { _this.delete(); });
    },

    // ... save, update

    delete : function () {
        var id = $('#id').val();

        $.ajax({
            type: 'DELETE',
            url: '/api/v1/posts/'+id,
            dataType: 'json',
            contentType:'application/json; charset=utf-8'
        }).done(function() {
            alert('글이 삭제되었습니다.');
            window.location.href = '/';
        }).fail(function (error) {
            alert(JSON.stringify(error));
        });
    }
};

main.init();

BackEnd

PostsAPIController

  • PostsAPIController
    • 게시글의 Id를 arguements로 받아 PostsService.delete(id)를 호출
    • URL을 Delete method 방식으로 호출하는 경우 게시글 삭제
@RequiredArgsConstructor
@RestController
public class PostsAPIController {

    private final PostsService postsService;

    // ... save, update, findById

    @DeleteMapping("/api/v1/posts/{id}")
    public Long delete(@PathVariable Long id) {
        postsService.delete(id);
        return id;
    }
}

PostsService

  • PostsService
    • postsRepository.delete(posts)
      • JpaRepository에서 이미 delete 메서드를 지원
      • 엔티티를 파라미터를 삭제할 수도 있고, deleteById 메서드를 이용하면 id로 삭제할 수도 있다.
      • 존재하는 Posts인지 확인하기 위해 Entity 조회 후 그대로 삭제
@RequiredArgsConstructor
@Service
public class PostsService {
    private final PostsRepository postsRepository;

    // ...     save, update, findById, findAllDesc

    @Transactional
    public void delete(Long id) {
        Posts posts = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시물이 없습니다. id=" + id));
        postsRepository.delete(posts);
    }
}

화면 확인

'Spring > SpringBoot' 카테고리의 다른 글

[SpringBoot] OAuth2 Google Login  (0) 2020.05.31
[SpringBoot] Spring Security & OAuth 2.0 로그인  (0) 2020.05.31
[SpringBoot] 게시글 수정  (0) 2020.05.29
[SpringBoot] 게시글 전체 조회  (0) 2020.05.29
[SpringBoot] 게시글 등록  (0) 2020.05.29

게시글 수정

  • FrontEnd
    • posts-udate.mustache 화면 개발
    • index.js 스크립트 내에 update 함수 추가
  • BackEnd
    • IndexController 내에 update 메서드 추가
    • PostsAPIController내에 postsService의 update 메서드 호출하는 update 메서드 추가

FrontEnd

index.mustache

  • index
    • <a href="/posts/update/{id}">
      • 타이틀(title)에 a tag를 추가
      • 타이틀을 클릭하면 개당 게시글의 수정 화면으로 이동
{{>layout/header}}

    <h1>스프링 부트로 시작하는 웹 서비스 No. 3</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>
            </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}}

posts-update.mustache

  • 게시글 수정

    1. {{post.id}}

      • mustache는 객체의 필드 접근 시 '.'(dot)으로 구분
      • 즉, Post 클래스의 id에 대한 접근은 post.id로 사용할 수 있다.
    2. readOnly

      • input 태그에 수정이 불가능하도록 하는 속성
      • id와 author는 수정할 수 없도록 readOnly 속성 추가
{{>layout/header}}

    <h1>게시글 수정</h1>

    <div class="col-md-12">
        <div class="col-md-4">
            <form>
                <div class="form-group">
                    <label for="title">글 번호</label>
                    <input type="text" class="form-control" id="id" value="{{post.id}}" readonly>
                </div>
                <div class="form-group">
                    <label for="title">제목</label>
                    <input type="text" class="form-control" id="title" value="{{post.title}}">
                </div>
                <div class="form-group">
                    <label for="author"> 작성자 </label>
                    <input type="text" class="form-control" id="author" value="{{post.author}}" readonly>
                </div>
                <div class="form-group">
                    <label for="content"> 내용 </label>
                    <textarea class="form-control" id="content">{{post.content}}</textarea>
                </div>
            </form>
            <a href="/" role="button" class="btn btn-secondary">취소</a>
            <button type="button" class="btn btn-primary" id="btn-update">수정 완료</button>
            <button type="button" class="btn btn-danger" id="btn-delete">삭제</button>
        </div>
    </div>

{{>layout/footer}}

index.js

  • index 객체 수정

    • update function 추가
    • title, content를 data로 설정하여 /api/v1/posts/{id} URL로 PUT 메서드 호출하는 스크립트 작성
    1. $("#btn-update").on("click")
      • btn-update란 id를 가진 HTML 엘리먼트에 click 이벤트가 발생할 때 update function을 실행하도록 이벤트 등록
    2. update : function()
      • 신규로 추가될 update function()
    3. type: "PUT"
      • 여러 HTTP Method 중 PUT 메서드를 선택
      • REST에서 CRUD는 다음과 같이 HTTP Method에 매핑된다.
        • 생성(Create) - POST
        • 읽기(Read) - GET
        • 수정(Update) - PUT
        • 삭제(Delete) - DELETE
    4. URL: "/api/v1/posts/" + id
      • 어느 게시글을 수정할 지 URL path로 구분하기 위해 Path에 id 값 추가
var index = {
    init : function () {
        var _this = this;
        // ... 
        $('#btn-update').on('click', function () { _this.update(); });
    },
    // ... save
    update : function () {
        var data = {
            title: $('#title').val(),
            content: $('#content').val()
        };
        var id = $('#id').val();
        $.ajax({
            type: 'PUT',
            url: '/api/v1/posts/'+id,
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            data: JSON.stringify(data)
        }).done(function() {
            alert('글이 수정되었습니다.');
            window.location.href = '/';
        }).fail(function (error) {
            alert(JSON.stringify(error));
        });
    },
};

index.init();

BackEnd

IndexController

  • IndexController
    • 게시글의 id로 /posts/update/{id} postsUpdate 메서드를 호출하는 메서드를 정의
    • 게시글을 가져와 model에 넣어 templates로 전달
@RequiredArgsConstructor
@Controller
public class IndexController {

    private final PostsService postsService;

    // ... index, save 

    @GetMapping("/posts/update/{id}")
    public String postsUpdate(@PathVariable Long id, Model model) {
        PostsResponseDto dto = postsService.findById(id);
        model.addAttribute("post", dto);
        return "posts-update";
    }
}

PostsAPIController

  • PostsAPIController
    • update메서드 호출로 게시글 수정
@RequiredArgsConstructor
@RestController
public class PostsAPIController {

    private final PostsService postsService;

    // ... save, findById

    @PutMapping("/api/v1/posts/{id}")
    public Long update(@PathVariable Long id, @RequestBody PostsUpdateRequestDto requestDto) {
        return postsService.update(id, requestDto);
    }
}

브라우저 확인

게시글 수정 페이지
게시글 수정 완료
변경 완료 확인

'Spring > SpringBoot' 카테고리의 다른 글

[SpringBoot] Spring Security & OAuth 2.0 로그인  (0) 2020.05.31
[SpringBoot] 게시글 삭제  (0) 2020.05.29
[SpringBoot] 게시글 전체 조회  (0) 2020.05.29
[SpringBoot] 게시글 등록  (0) 2020.05.29
[SpringBoot] Mustache  (0) 2020.05.28

게시글 전체조회

  • View template 수정
  • BackEnd
    • Posts List Dto 생성
    • Controller, Service, Repository Query 생성

View

  • Template 수정
    • Posts를 보여주기위한 table 구성

index.mustache

  • Mustache 문법
    1. {{#posts}}
      • posts라는 List를 순회
      • Java의 for문과 동일하게 작동
    2. {{id}}등의 {{변수명}}
      • List에서 뽑아낸 객체의 필드를 사용
{{>layout/header}}

    <h1>스프링 부트로 시작하는 웹 서비스 No. 3</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>
            </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}}

BackEnd

PostsListResponseDto

  • PostsListResponseDto
    • Posts의 Entity를 이용하여 필요한 필드만 Dto로 구성
@Getter
public class PostsListResponseDto {
    private Long id;
    private String title;
    private String author;
    private LocalDateTime modifiedDate;

    public PostsListResponseDto(Posts entity) {
        this.id = entity.getId();
        this.title = entity.getTitle();
        this.author = entity.getAuthor();
        this.modifiedDate = entity.getModifiedDate();
    }
}

PostsRepository

  • PostsRepository

    • JpaRepository 인터페이스에 Entity에 접근하여 가져오는 findAll() 메서드가 있다.
    • Spring Data JPA에서 제공하지 않는 메서드를 사용하기 위해서 @Query를 사용하는 방법도 있다.
    • findAllDesc을 새로 작성하여 PostsListResponseDto라는 Controller와 Service에서 접근가능한 Dto를 사용하여 호출
    • @Query가 가독성이 더 좋을 수도 있다.
  • Entity 클래스만으로 처리하기 어려운 경우

    • querydsl, jooq, MyBatis 등 프레임워크를 추가하여 조회용으로 사용할 수 있다.
    • 기본적인 등록 / 수정 / 삭제는 Spring Data JPA만으로도 충분히 가능하다.
  • querydsl을 추천하는 이유

    • 타입의 안정성
      • 단순한 문자열로 쿼리를 생성하는 것이 아니라, 메서드를 기번으로 쿼리를 생성
      • 오타나 존재하지 않는 컬럼명을 명시하는 경우 IDE에서 자동으로 검증이 가능하다.
public interface PostsRepository extends JpaRepository<Posts, Long> {
    @Query("SELECT p FROM Posts p ORDER BY p.id DESC")
    List<Posts> findAllDesc();
}

PostsService

  • PostsService

    • PostsRepository에서 구현한 findAllDesc() 메서드를 호출
    • List<Posts> 를 PostsListResponseDto로 매핑하여 List<PostsResponseDto>로 리턴
    • findAllDesc() 메서드의 트랜잭션 어노테이션에 readOnly = true라는 옵션을 추가
      - 이는 트랜잭션 범위는 유지하되, 조회 기능만 남겨두어 조회 속도를 개선할 수 있다.
      • 등록, 수정, 삭제 기능이 전혀없는 서비스 메서드에서 사용하는 것을 추천
  • 람다 설명

    - .map(PostsListResponseDto::new)
    - .map(posts -> new PostsListResponseDto(posts))
    - postsRepository  결과로 넘어온 Posts의 Stream을 map을 통해 PostsListReponseDto로 변환 -> List로 반환하는 메서드
@RequiredArgsConstructor
@Service
public class PostsService {
    private final PostsRepository postsRepository;

    // ... save, update, findById

    @Transactional(readOnly = true)
    public List<PostsListResponseDto> findAllDesc() {
        return postsRepository.findAll().stream()
                .map(PostsListResponseDto::new)
                .collect(Collectors.toList());
    }
}

IndexController

  • IndexController
    • Service Layer에서 List<PostsListResponseDto> 를 반환하는 findAllDesc()를 model에 담아 View로 전달한다.
    • Model
      • 서버 템플릿 엔진에서 사용할 수 있는 객체를 저장
      • postsService.findAllDesc()로 가져온 결과를 posts로 index.mustache에 전달
@RequiredArgsConstructor
@Controller
public class IndexController {

    private final PostsService postsService;

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

    //... save
}

게시글 화면 확인

'Spring > SpringBoot' 카테고리의 다른 글

[SpringBoot] 게시글 삭제  (0) 2020.05.29
[SpringBoot] 게시글 수정  (0) 2020.05.29
[SpringBoot] 게시글 등록  (0) 2020.05.29
[SpringBoot] Mustache  (0) 2020.05.28
[SpringBoot] JPA Auditing  (0) 2020.05.28

Mustache를 활용한 게시글 등록화면 만들기

  • HTML
    • Layout 방식을 활용하여 공통 영역을 별도의 파일로 분리하여 필요한 곳에서 가져다 쓰는 방식 활용
    • footer, header 공통 영역을 분리
    • src/main/resources/templates 디렉토리에 layout 디렉토리를 추가로 생성하여 저장
  • CSS, JavaScript
    • BootStrap, JQuery 등 프론트엔드 라이브러리를 사용
    • 여기서는 외부 CDN을 사용하여 개발, 실제 서비스에서는 직접 라이브러리를 받아서 사용
    • 페이지 로딩속도를 높이기 위해 css 태그는 header, js 태그는 footer에 위치
    • HTML은 인터프리터언어로 소스코드를 위에서 아래로 읽고 실행하기 때문에 css를 읽지않고는 깨진화면이 보여질 수 있다.
    • JavaScript의 위치가 Header에 있을 경우 script 오류가 발생하는 경우 화면자체가 나오지 않을 수 있다.

IndexController

@RequiredArgsConstructor
@Controller
public class IndexController {

    @GetMapping
    public String index() {
        return "index";
    }

    @GetMapping
    public String postsSave() {
        return "posts-save";
    }
}

View Page

  • 스프링 부트는 기본적으로 src/main/resources/static에 위치한 정적 자원을 호출한다.
    • 자바스크립트, CSS, 이미지 등 정적 파일들은 URL에서 /로 설정된다.
    • src/main/resources/static/js
    • src/main/resources/static/css
    • src/main/resources/static/image

posts-save.mustache

  • posts-save
{{>layout/header}}

<h1>게시글 등록</h1>

<div class="col-md-12">
    <div class="col-md-4">
        <form>
            <div class="form-group">
                <label for="title">제목</label>
                <input type="text" class="form-control" id="title" placeholder="제목을 입력하세요">
            </div>
            <div class="form-group">
                <label for="author"> 작성자 </label>
                <input type="text" class="form-control" id="author" placeholder="작성자를 입력하세요">
            </div>
            <div class="form-group">
                <label for="content"> 내용 </label>
                <textarea class="form-control" id="content" placeholder="내용을 입력하세요"></textarea>
            </div>
        </form>
        <a href="/" role="button" class="btn btn-secondary">취소</a>
        <button type="button" class="btn btn-primary" id="btn-save">등록</button>
    </div>
</div>
{{>layout/footer}}

index.js

  • index
    • 프로토타입 기반의 객체지향 언어로 사용
    • index이라는 객체 리터럴에 init, save 내부 함수를 생성
    • init 함수에는 id 값이 btn-save인 부분의 click 이벤트가 발생하는 경우 save 함수를 호출
    • save 함수는 title, author, content를 data라는 객체로 저장하여 /api/v1/posts URL로 AJAX 호출하여 게시글을 등록
var index = {
    init : function () {
        var _this = this;
        $('#btn-save').on('click', function () { _this.save(); });
    },
    save : function () {
        var data = {
            title: $('#title').val(),
            author: $('#author').val(),
            content: $('#content').val()
        };

        $.ajax({
            type: 'POST',
            url: '/api/v1/posts',
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            data: JSON.stringify(data)
        }).done(function() {
            alert('글이 등록되었습니다.');
            window.location.href = '/';
        }).fail(function (error) {
            alert(JSON.stringify(error));
        });
    },
};

index.init();

게시글 등록 페이지
게시글 등록 확인

게시글 등록 DB 확인

  • 게시글 등록확인

게시글 등록확인

'Spring > SpringBoot' 카테고리의 다른 글

[SpringBoot] 게시글 수정  (0) 2020.05.29
[SpringBoot] 게시글 전체 조회  (0) 2020.05.29
[SpringBoot] Mustache  (0) 2020.05.28
[SpringBoot] JPA Auditing  (0) 2020.05.28
[SpringBoot] Posts API 만들기  (2) 2020.05.28

+ Recent posts