스프링 부트 백엔드 개발 강좌, OAuth2로 로그인 로그아웃 구현, 의존성 추가하기

저자: 조광형

날짜: [현재 날짜]

1. 서론

현대 애플리케이션은 사용자 인증과 권한 부여를 위해 OAuth2 프로토콜을 많이 사용합니다. 이 프로토콜은 다양한 클라이언트 애플리케이션에서 안전하고 유연한 방식으로 사용자 정보를 처리할 수 있도록 도와줍니다. 본 강좌에서는 스프링 부트를 활용하여 OAuth2를 기반으로 한 로그인과 로그아웃 기능을 구현하는 방법을 단계별로 안내합니다.

2. 스프링 부트 프로젝트 시작하기

스프링 부트 프로젝트를 시작하기 위해서는 첫 단계로 Spring Initializr를 이용하여 기본 프로젝트 구조를 생성합니다. 다음은 초기 설정 절차입니다.

  1. 웹 브라우저를 열고 Spring Initializr에 접속합니다.
  2. 프로젝트 메타데이터를 설정합니다:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 최신 안정 버전
    • Group: com.example
    • Artifact: oauth2-demo
    • Name: oauth2-demo
    • Description: OAuth2 예제 애플리케이션
  3. Dependencies 섹션에서 다음 의존성을 추가합니다:
    • Spring Web
    • Spring Security
    • Spring Boot DevTools
    • Spring Data JPA
    • H2 Database (개발 및 테스트를 위한 인메모리 데이터베이스)
  4. ‘Generate’를 클릭하여 ZIP 파일을 다운로드하고, 이를 원하는 디렉터리에 압축 해제합니다.

3. 의존성 추가하기

이제 Maven의 pom.xml 파일을 열고 OAuth2 관련 의존성을 추가합니다. 다음 코드를 pom.xml의 `` 섹션에 추가하십시오.

                
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-oauth2-client</artifactId>
                    </dependency>

                    <dependency>
                        <groupId>org.springframework.security</groupId>
                        <artifactId>spring-security-oauth2-client</artifactId>
                    </dependency>

                    <dependency>
                        <groupId>org.springframework.security</groupId>
                        <artifactId>spring-security-oauth2-jose</artifactId>
                    </dependency>
                
            

위의 의존성을 추가하면 OAuth2 클라이언트의 기본 설정을 사용할 수 있습니다. 그 다음으로는 JpaRepository를 사용하여 사용자 정보를 저장할 수 있는 엔티티를 생성해야 합니다.

4. 사용자 엔티티 및 리포지토리 설정하기

애플리케이션의 사용자 정보를 저장하기 위한 엔티티 클래스를 생성합니다. 아래 코드는 사용자 정보를 담을 User 엔티티의 예입니다.

                
                    package com.example.oauth2demo.model;

                    import javax.persistence.Entity;
                    import javax.persistence.GeneratedValue;
                    import javax.persistence.GenerationType;
                    import javax.persistence.Id;

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

                        private String email;
                        private String name;

                        // Getters and Setters
                    }
                
            

다음으로, User 엔티티에 대한 JpaRepository를 생성합니다.

                
                    package com.example.oauth2demo.repository;

                    import com.example.oauth2demo.model.User;
                    import org.springframework.data.jpa.repository.JpaRepository;

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

5. OAuth2 설정하기

OAuth2 로그인 기능을 추가하기 위해, application.yml 파일에 OAuth2 클라이언트를 설정해야 합니다. 아래의 예시를 참고하세요.

                
                    spring:
                      security:
                        oauth2:
                          client:
                            registration:
                              google:
                                client-id: YOUR_CLIENT_ID
                                client-secret: YOUR_CLIENT_SECRET
                                scope:
                                  - email
                                  - profile
                            provider:
                              google:
                                authorization-uri: https://accounts.google.com/o/oauth2/auth
                                token-uri: https://oauth2.googleapis.com/token
                                user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
                                user-name-attribute: sub
                
            

여기에 본인의 Google API 클라이언트를 등록해야 합니다. Google Cloud Console에서 클라이언트를 생성하여 client-id와 client-secret을 얻을 수 있습니다.

6. 보안 구성하기

스프링 시큐리티를 설정하여 OAuth2 로그인과 로그아웃을 처리하는 방법을 다루겠습니다. SecurityConfig 클래스를 작성하고, HTTP 보안 관련 설정을 추가합니다.

                
                    package com.example.oauth2demo.config;

                    import org.springframework.context.annotation.Bean;
                    import org.springframework.context.annotation.Configuration;
                    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;

                    @Configuration
                    @EnableWebSecurity
                    public class SecurityConfig extends WebSecurityConfigurerAdapter {
                        @Override
                        protected void configure(HttpSecurity http) throws Exception {
                            http
                                .authorizeRequests()
                                    .antMatchers("/", "/login", "/oauth2/**").permitAll()
                                    .anyRequest().authenticated()
                                .and()
                                    .oauth2Login()
                                        .defaultSuccessUrl("/home", true)
                                .and()
                                    .logout()
                                        .logoutSuccessUrl("/");
                        }
                    }
                
            

이 설정을 통해 루트와 로그인 페이지, 그리고 OAuth2 관련 URL은 누구나 접근할 수 있으며, 인증된 사용자만 다른 페이지에 접근할 수 있도록 구성합니다.

7. 컨트롤러 작성하기

사용자가 OAuth2 로그인을 하고 나서 적절한 페이지로 리다이렉트되도록 컨트롤러를 작성해야 합니다. 아래는 기본적인 컨트롤러의 예입니다.

                
                    package com.example.oauth2demo.controller;

                    import org.springframework.stereotype.Controller;
                    import org.springframework.web.bind.annotation.GetMapping;

                    @Controller
                    public class MainController {
                        @GetMapping("/")
                        public String index() {
                            return "index"; // index.html 페이지 반환
                        }

                        @GetMapping("/home")
                        public String home() {
                            return "home"; // home.html 페이지 반환
                        }
                    }
                
            

이 컨트롤러는 기본 루트 경로와 home 경로를 위해 각각 index.html과 home.html 페이지를 반환합니다.

8. 뷰 템플릿 설정하기

Thymeleaf를 사용하여 View 템플릿을 설정합니다. resources/templates 폴더에 index.html과 home.html을 생성합니다. 아래는 각 파일의 샘플 코드입니다.

                
                    <!-- index.html -->
                    <!DOCTYPE html>
                    <html xmlns:th="http://www.thymeleaf.org">
                    <head>
                        <title>OAuth2 로그인 예제</title>
                    </head>
                    <body>
                        <h1>환영합니다!</h1>
                        <a th:href="@{/oauth2/authorization/google}">구글 로그인</a>
                    </body>
                    </html>
                
            
                
                    <!-- home.html -->
                    <!DOCTYPE html>
                    <html xmlns:th="http://www.thymeleaf.org">
                    <head>
                        <title>홈 화면</title>
                    </head>
                    <body>
                        <h1>홈에 오신 것을 환영합니다!</h1>
                        <a href="/logout">로그아웃</a>
                    </body>
                    </html>
                
            

9. 애플리케이션 실행하기

모든 설정이 완료되었다면 애플리케이션을 실행해보세요. IDE에서 메인 클래스를 실행하거나, 터미널에서 다음 명령어를 통해 실행할 수 있습니다.

                
                    mvn spring-boot:run
                
            

애플리케이션이 정상적으로 실행되면 웹 브라우저에서 http://localhost:8080에 접속하여 로그인 화면을 확인할 수 있습니다.

10. 결론

본 강좌에서는 스프링 부트를 이용한 OAuth2 로그인/로그아웃 기능의 구현 과정을 살펴보았습니다. 이 예제는 기본적인 설정에 대한 소개이며, 실제 프로젝트에서는 추가적인 보안 설정이나 사용자 데이터의 저장 및 관리를 고려해야 합니다. 여러분의 프로젝트에 맞는 방식으로 OAuth2를 확장하고 사용자 인증 기능을 구현해 보시길 바랍니다.

이 강좌가 도움이 되었기를 바랍니다. 질문이나 피드백은 댓글에 남겨주세요.

스프링 부트 백엔드 개발 강좌, OAuth2로 로그인 로그아웃 구현, 쿠키 관리 클래스 구현하기

안녕하세요! 이번 글에서는 스프링 부트를 이용한 백엔드 개발에서 OAuth2를 활용한 로그인 및 로그아웃 구현 방법과 쿠키 관리 클래스의 구현에 대해 상세히 알아보겠습니다. 웹 애플리케이션에서 사용자 인증 및 세션 관리는 매우 중요한 요소입니다. 이 글에서는 이를 위한 다양한 개념과 기술 스택을 소개할 것입니다.

목차

  1. 1. OAuth2 개요
  2. 2. 스프링 부트 설정
  3. 3. OAuth2 로그인 기능 구현하기
  4. 4. 로그아웃 기능 구현하기
  5. 5. 쿠키 관리 클래스 구현하기
  6. 6. 결론

1. OAuth2 개요

OAuth2는 주로 API 인증 및 권한 부여에 사용되는 프로토콜입니다. 마치 타인의 정보를 안전하게 접근할 수 있는 중재자인 역할을 합니다. 이 프로토콜은 인증을 제3의 서비스 제공자에게 위임하고, 사용자 정보를 보호하는 데 도움을 줍니다.

예를 들어, 사용자가 Google 계정을 사용하여 다른 웹사이트에 로그인할 수 있게 할 때 OAuth2를 사용하는 방식입니다. 이 방식은 사용자에게 편리함을 제공할 뿐만 아니라, 개발자가 직접 비밀번호를 다루지 않아도 되는 장점이 있습니다.

1.1 OAuth2의 주요 용어

  • Resource Owner: 사용자, 즉 자원의 소유자.
  • Client: 사용자 정보를 요청하는 애플리케이션.
  • Authorization Server: 사용자 인증을 수행하고, Access Token을 발급하는 서버.
  • Resource Server: 보호된 자원에 대한 접근을 허가하는 서버.
  • Access Token: 리소스 서버에 접근하기 위한 인증 토큰.

2. 스프링 부트 설정

스프링 부트를 이용해 OAuth2를 구현하기 위해 필요한 의존성을 추가하겠습니다. spring-boot-starter-oauth2-clientspring-boot-starter-security를 포함해야 합니다.

pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

이 외에도 MVC 및 Thymeleaf 템플릿 엔진을 사용할 계획이라면 추가로 다음 의존성도 포함시켜야 합니다.


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

스프링 부트의 설정 파일인 application.yml에 OAuth2 관련 설정을 추가해야 합니다. 예를 들어, Google 로그인을 설정할 수 있습니다.

application.yml:
spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope: profile, email
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo

3. OAuth2 로그인 기능 구현하기

OAuth2 로그인을 구현하기 위해 필요한 설정을 마쳤다면, 이제 로그인 페이지를 만들어 보겠습니다. Thymeleaf를 이용해 간단한 로그인 버튼을 추가해줄 수 있습니다.

login.html:
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>로그인 페이지</title>
</head>
<body>
    <h1>로그인하세오</h1>
    <a href="@{/oauth2/authorization/google}">Google로 로그인</a>
</body>
</html>

위 코드에서 Google로 로그인하라는 링크를 클릭하면 OAuth2 플로우가 시작됩니다. 사용자가 Google에 로그인하고 권한을 허용하면, 해당 사용자의 정보가 애플리케이션으로 돌아옵니다.

3.1 사용자 정보 가져오기

로그인 후 사용자 정보를 가져오기 위해, 스프링 시큐리티의 UserDetailsService 또는 OAuth2UserService를 구현할 수 있습니다.

UserService.java:
@Service
public class UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2User oAuth2User = super.loadUser(userRequest);
        
        // 사용자 정보를 활용한 비즈니스 로직 추가
        
        return oAuth2User;
    }
}

이제 사용자가 로그인할 때마다 해당 서비스가 호출되어 사용자의 정보를 처리할 수 있게 됩니다.

4. 로그아웃 기능 구현하기

이제 로그아웃 기능을 구현해보겠습니다. 로그아웃은 사용자 세션을 종료시키고, 이를 통해 사용자 정보가 더 이상 유효하지 않게 됩니다.

LogoutController.java:
@Controller
public class LogoutController {

    @GetMapping("/logout")
    public String logout() {
        SecurityContextHolder.clearContext();
        // 추가적인 로그아웃 처리 로직
        return "redirect:/";
    }
}

로그아웃 후 사용자를 홈 페이지로 리다이렉트합니다. 로그아웃을 위한 버튼을 아래와 같이 만들 수 있습니다.

login.html:
<a href="@{/logout}">로그아웃</a>

5. 쿠키 관리 클래스 구현하기

이제는 사용자의 세션과 데이터를 효율적으로 관리하기 위해 쿠키 관리 클래스를 구현해보겠습니다. 쿠키는 클라이언트 측에서 작은 데이터를 저장하는 방법으로, 사용자 상태를 유지하는 데 유용합니다.

CookieManager.java:
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class CookieManager {

    public void createCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public String readCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public void deleteCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}

위의 CookieManager 클래스는 쿠키 생성, 읽기 및 삭제를 위한 다양한 메서드를 제공합니다.

5.1 쿠키 활용 예제

이제 쿠키를 실제로 사용하는 예제를 살펴보겠습니다. 사용자가 로그인할 때, 특정 정보를 쿠키에 저장할 수 있습니다.

LoginController.java:
@PostMapping("/login")
public String login(@RequestParam String username, HttpServletResponse response) {
    // 로그인 로직
    
    cookieManager.createCookie(response, "username", username, 60 * 60); // 1시간 유지
    return "redirect:/home";
}

이렇게 생성된 쿠키는 사용자의 브라우저에 저장되며, 이후 요청 시에 이를 쉽게 읽어올 수 있습니다.

6. 결론

이번 글에서는 스프링 부트를 사용하여 OAuth2 기반의 로그인 및 로그아웃 기능을 구현하고, 사용자 세션 관리를 위한 쿠키 관리 클래스를 구체적으로 알아보았습니다. OAuth2를 통해 인증을 쉽게 해결하고, 효과적인 쿠키 관리를 통해 사용자 경험을 개선할 수 있습니다.

이제 여러분은 스프링 부트를 기반으로 한 웹 애플리케이션에서 OAuth2와 쿠키 관리를 통한 사용자 인증 및 세션 관리 기능을 구현할 수 있는 능력을 갖추셨습니다. 이 글이 여러분의 개발 여정에 도움이 되기를 바랍니다.

스프링 부트 백엔드 개발 강좌, OAuth2로 로그인 로그아웃 구현, 글에 글쓴이 추가하기

안녕하세요! 이번 글에서는 스프링 부트를 사용하여 백엔드 개발을 하는 방법에 대해 자세히 알아보겠습니다. 특히 OAuth2를 활용하여 사용자 인증 기능을 구현하고, 사용자가 작성한 글에 글쓴이 정보를 추가하는 방법을 다루겠습니다.

1. 스프링 부트란?

스프링 부트는 복잡한 설정을 최소화하고 빠른 애플리케이션 개발을 가능하게 해주는 프레임워크입니다. 스프링 프레임워크를 기반으로 하며, 자주 사용되는 라이브러리와 설정을 내장하고 있어 매우 효율적으로 웹 애플리케이션을 개발할 수 있습니다.

1.1. 스프링 부트의 장점

  • 제공되는 스타터 의존성으로 빠르고 쉽게 시작할 수 있습니다.
  • 자동 구성 기능으로 복잡한 설정을 줄일 수 있습니다.
  • 내장 서버를 통해 별도의 서버 설정 없이도 실행할 수 있습니다.
  • 스프링에 대한 깊은 이해가 없더라도 개발이 가능합니다.

2. OAuth2란 무엇인가?

OAuth2는 리소스 소유자가 자원에 대한 접근을 제3자 애플리케이션에 허가할 수 있도록 도와주는 인증 및 권한 부여 프로토콜입니다. 웹 애플리케이션, 모바일 애플리케이션 등 다양한 환경에서 사용자 인증을 쉽게 구현할 수 있게 해줍니다.

2.1. OAuth2의 주요 구성 요소

  • Resource Owner: 보호된 리소스에 대한 접근을 허가하는 사용자.
  • Client: 자원 소유자의 권한을 받아서 자원에 접근하는 애플리케이션.
  • Authorization Server: 인증을 처리하고, 토큰을 발급하는 서버.
  • Resource Server: 보호된 리소스를 저장하고 있는 서버.

3. 프로젝트 설정

스프링 부트를 이용한 프로젝트 개발을 시작하기 위해 Spring Initializr를 사용합니다. 다음과 같은 의존성을 선택해 주세요:

  • Spring Web
  • Spring Security
  • Spring Data JPA
  • H2 Database (테스트 목적)
  • OAuth2 Client

프로젝트를 생성한 후, 필요한 라이브러리를 Maven 또는 Gradle을 통해 추가합니다.

3.1. 주요 의존성 추가 (pom.xml 예시)


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
    </dependency>
</dependencies>

4. 사용자 인증을 위한 OAuth2 설정

4.1. application.yml 설정

OAuth2를 사용할 외부 서비스 (예: Google, GitHub 등)에 대한 클라이언트 정보를 application.yml 파일에 설정합니다.


spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope: profile, email
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/userinfo/v2/me

4.2. Security Configuration 설정

스프링 시큐리티를 설정하여 OAuth2 로그인 기능을 구현합니다.


import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorizeRequests ->
                authorizeRequests
                    .antMatchers("/", "/login", "/perform_login").permitAll()
                    .anyRequest().authenticated()
            )
            .oauth2Login(oauth2 -> oauth2
                .loginPage("/login")
            );
    }
}

5. 로그인 및 로그아웃 기능 구현

5.1. Custom Login Page 만들기

HTML과 CSS를 이용하여 커스텀 로그인 페이지를 생성합니다. 예제는 다음과 같습니다:


<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로그인 페이지</title>
</head>
<body>
    <h1>로그인 페이지</h1>
    <a href="/oauth2/authorization/google">Google로 로그인</a>
</body>
</html>

5.2. 로그아웃 처리하기

로그아웃 기능을 설정하려면, 다음과 같이 SecurityConfig를 수정합니다.


@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests(authorizeRequests ->
            authorizeRequests
                .antMatchers("/", "/login", "/perform_login").permitAll()
                .anyRequest().authenticated()
        )
        .oauth2Login(oauth2 -> oauth2
            .loginPage("/login")
        )
        .logout(logout -> logout
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login?logout")
        );
}

6. 글쓰기 기능 구현

이제 사용자가 작성한 글을 데이터베이스에 저장하기 위한 기능을 구현합니다.

6.1. Entity 클래스 생성

글 작성자를 포함한 글(Post)을 위한 Entity 클래스를 생성합니다.


import javax.persistence.*;

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String content;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private User author;

    // Getters and Setters
}

6.2. User Entity 생성


import javax.persistence.*;

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

    private String username;
    private String email;

    // Getters and Setters
}

6.3. Repository 및 Service 생성

글 작성을 위한 Repository와 Service 클래스를 생성합니다.


// PostRepository.java
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository<Post, Long> {
}

// PostService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostService {
    @Autowired
    private PostRepository postRepository;

    public List<Post> findAll() {
        return postRepository.findAll();
    }

    public Post save(Post post) {
        return postRepository.save(post);
    }
}

6.4. Controller 생성

사용자가 글을 작성하고 조회할 수 있도록 Controller를 생성합니다.


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/posts")
public class PostController {
    @Autowired
    private PostService postService;

    @GetMapping
    public List<Post> getAllPosts() {
        return postService.findAll();
    }

    @PostMapping
    public Post createPost(@RequestBody Post post) {
        return postService.save(post);
    }
}

7. 결론

이번 글에서는 스프링 부트를 이용한 백엔드 개발의 기초와 OAuth2를 활용한 사용자 인증 및 글쓰기 기능 구현 방법에 대해 알아보았습니다. OAuth2를 통해 다양한 소셜 미디어 로그인 기능을 쉽게 구현할 수 있으며, 사용자 친화적인 웹 어플리케이션 개발에 큰 도움이 될 것입니다. 다음 강좌에서는 프론트엔드와의 연동, 더 나아가 배포에 대한 내용을 다룰 예정입니다. 이 글이 도움이 되셨길 바라며, 질문 사항이 있으면 언제든지 댓글로 남겨주세요!

스프링 부트 백엔드 개발 강좌, OAuth2로 로그인 로그아웃 구현, 스프링 시큐리티로 OAuth2를 구현하고 적용하기

1. 서론

현대 애플리케이션의 인증(Authentication) 및 인가(Authorization) 메커니즘은 매우 중요합니다. OAuth2는
다양한 플랫폼에서 인증 및 인가를 처리하기 위한 널리 사용되는 프레임워크입니다. 본 강좌에서는 스프링 부트
와 스프링 시큐리티를 사용하여 OAuth2를 통한 로그인 및 로그아웃 과정을 단계별로 설명하겠습니다. 목표는
사용자 인증 기능을 포함한 안전한 API를 구축하는 것입니다.

2. 스프링 부트 및 스프링 시큐리티 프로젝트 설정

2.1. 설치 요구 사항

본 강좌를 진행하기 위해서는 다음의 소프트웨어가 필요합니다:

  • JDK 11 이상
  • Apache Maven
  • IDE (IntelliJ IDEA, Eclipse 등)

2.2. 프로젝트 생성

먼저, Spring Initializr를 사용하여 새로운 스프링 부트 프로젝트를 생성합니다. 의존성으로는
Spring Web, Spring Security, OAuth2 Client를 추가합니다.

mvn clean install

3. OAuth2 인증 설정

3.1. OAuth2 제공자 구성

다양한 OAuth2 제공자가 있으며, 이번 강좌에서는 Google OAuth2를 사용할 것입니다. Google Cloud Console에서
새로운 프로젝트를 생성하고 OAuth 2.0 클라이언트 ID를 생성합니다.
필요한 정보는 클라이언트 ID와 클라이언트 비밀입니다.

3.2. 애플리케이션 프로퍼티 설정

src/main/resources/application.yml 파일에 다음과 같은 설정을 추가합니다:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope:
              - profile
              - email
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/userinfo/email
            user-name-attribute: email

4. 스프링 시큐리티 설정

4.1. 시큐리티 설정 클래스 생성

스프링 시큐리티의 기본 설정을 위해 SecurityConfig라는 클래스를 생성합니다. 이 클래스는
WebSecurityConfigurerAdapter를 확장하여 시큐리티 구성을 정의합니다.

import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/", "/login", "/oauth2/**").permitAll() // 로그인과 관련된 경로는 모든 사용자에게 허용
            .anyRequest().authenticated() // 그 외의 요청은 인증된 사용자만 접근 가능
            .and()
            .oauth2Login(); // OAuth2 로그인 설정
    }
}

5. 로그인 및 로그아웃

5.1. 로그인 처리

OAuth2 로그인 처리는 스프링 시큐리티가 자동으로 관리합니다. 사용자가 /login 경로로 접근하면 로그인 페이지를
제공하고, 로그인 후에는 Redirect URI로 설정한 경로로 리다이렉트 됩니다.

5.2. 로그아웃 처리

로그아웃은 logout 경로를 설정하여 간단하게 처리할 수 있습니다. 로그아웃 후 사용자를
홈 페이지로 리다이렉트 할 수 있습니다.

http.logout()
        .logoutSuccessUrl("/") // 로그아웃 시 홈으로 리다이렉트
        .invalidateHttpSession(true); // 세션 무효화

6. 클라이언트 애플리케이션 생성

로그인과 로그아웃을 테스트하기 위해 간단한 클라이언트 애플리케이션을 생성합니다. 사용자는 Google
계정을 통해 인증한 후 본인 정보를 확인할 수 있습니다.

import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.userdetails.OAuth2UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    private final OAuth2UserService oAuth2UserService;
    private final ClientRegistrationRepository clientRegistrationRepository;

    public UserController(OAuth2UserService oAuth2UserService, ClientRegistrationRepository clientRegistrationRepository) {
        this.oAuth2UserService = oAuth2UserService;
        this.clientRegistrationRepository = clientRegistrationRepository;
    }

    @GetMapping("/user")
    public String getUserInfo(Principal principal) {
        return "User Info: " + principal.getName(); // 사용자 정보 리턴
    }
}

7. 테스트 및 결론

모든 설정이 완료되었으면 애플리케이션을 실행하여
/login 페이지로 접속합니다. Google 로그인 버튼을 클릭하여 인증 과정이 올바르게 진행되는지 확인하세요.
로그인이 성공하면 /user 경로에서 사용자 정보를 확인할 수 있습니다.

이번 강좌를 통해 스프링 부트를 사용한 OAuth2 로그인/로그아웃 기초를 배웠습니다. 향후에는 JWT를
활용한 더 복잡한 인증 메커니즘으로 확장할 수 있으며, 회사의 요구 사항에 맞는 사용자 정의 기능을 추가할
수 있습니다.

© 2023 스프링 부트 개발 블로그

스프링 부트 백엔드 개발 강좌, OAuth2로 로그인 로그아웃 구현, 글 수정, 삭제, 글쓴이 확인 로직 추가하기

목차

  1. 소개
  2. 스프링 부트 소개
  3. OAuth2 개요
  4. 로그인/로그아웃 구현
  5. 글 수정 및 삭제 기능 구현
  6. 글쓴이 확인 로직 추가
  7. 결론

소개

오늘은 스프링 부트를 사용하여 백엔드 애플리케이션을 개발하는 방법을 알아보겠습니다. 이번 강좌에서는 OAuth2를 통한 로그인 및 로그아웃 구현 방법과 글 수정 및 삭제 기능, 그리고 글쓴이 확인 로직을 추가하는 방법을 다룰 것입니다. 이 과정을 통해 스프링 부트의 다양한 기능을 활용하는 방법을 배울 수 있습니다.

스프링 부트 소개

스프링 부트는 스프링 프레임워크를 기반으로 한 간편한 애플리케이션 개발을 지원하는 프레임워크입니다. 복잡한 설정 없이 빠르게 애플리케이션을 구축할 수 있도록 도와주며, 다양한 내장 서버(예: Tomcat, Jetty 등)를 지원합니다. 스프링 부트의 주요 이점은 다음과 같습니다:

  • 빠른 시작: 초기 설정이 간편하여 개발 시간을 단축할 수 있습니다.
  • 자동 구성: 필요한 라이브러리와 의존성을 자동으로 설정해줍니다.
  • 내장 서버: 별도의 서버 설정 없이 로컬에서 쉽게 애플리케이션을 실행할 수 있습니다.
  • 강력한 커뮤니티: 활발한 사용자와 풍부한 자료가 많아 학습과 문제 해결에 도움이 됩니다.

OAuth2 개요

OAuth2는 클라이언트 애플리케이션이 사용자 자원에 접근할 수 있도록 권한을 부여하는 인증 프로토콜입니다. OAuth2를 통해 사용자는 애플리케이션에 대한 접근 권한을 안전하게 관리할 수 있습니다. OAuth2는 여러 인증 방식(예: Authorization Code, Implicit, Resource Owner Password Credentials 등)을 지원하며, 일반적으로 웹 애플리케이션과 모바일 애플리케이션에서 많이 사용됩니다.

이번 강좌에서는 OAuth2를 사용하여 사용자 인증을 구현하고, 이 인증 정보를 가지고 글을 작성, 수정, 삭제하는 기능을 추가할 것입니다. 우리는 기본적으로 Authorization Code Grant 방식을 사용할 것입니다.

로그인/로그아웃 구현

스프링 부트 애플리케이션에 OAuth2 기반의 로그인/로그아웃 기능을 구현하는 방법을 살펴보겠습니다. 이 과정에서 스프링 시큐리티(Spring Security)를 사용하여 인증 및 권한 부여를 처리할 것입니다. 다음 단계로 진행해 보겠습니다.

1. 의존성 추가

우선, Maven pom.xml 파일에 필요한 의존성을 추가해야 합니다. 다음의 의존성을 추가하세요:


      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-oauth2-client</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
    

2. application.yml 설정

이제 oauth2 클라이언트 정보를 설정해야 합니다. src/main/resources/application.yml 파일에 다음과 같이 설정하세요:


    spring:
      security:
        oauth2:
          client:
            registration:
              google:
                client-id: YOUR_CLIENT_ID
                client-secret: YOUR_CLIENT_SECRET
                scope: profile, email
                redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
                authorization-grant-type: authorization_code
            provider:
              google:
                authorization-uri: https://accounts.google.com/o/oauth2/auth
                token-uri: https://oauth2.googleapis.com/token
                user-info-uri: https://www.googleapis.com/userinfo/v2/me
    

3. SecurityConfig 클래스 작성

안전한 애플리케이션 구성을 위해 SecurityConfig 클래스를 생성합니다. 이 클래스는 스프링 시큐리티의 보안 설정을 담당합니다.


    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    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;

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/", "/login", "/error/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .oauth2Login()
                    .defaultSuccessUrl("/home", true)
                    .failureUrl("/login?error");
        }
    }
    

4. 로그인 및 로그아웃 컨트롤러 구현

사용자가 로그인을 시도할 때 호출되는 HomeController 클래스를 생성하여 로그인 후의 흐름을 처리합니다.


    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;

    @Controller
    public class HomeController {

        @GetMapping("/")
        public String index() {
            return "index"; // index.html 페이지로 리턴
        }

        @GetMapping("/home")
        public String home() {
            return "home"; // home.html 페이지로 리턴
        }
    }
    

여기까지 입력하면 기본 로그인 및 로그아웃 기능이 구현되었습니다. 이제 사용자가 Google 계정을 통해 로그인할 수 있습니다.

글 수정 및 삭제 기능 구현

이제 기본적인 로그인/로그아웃 기능을 구현했으니, 다음으로는 글 작성, 수정 및 삭제 기능을 추가하겠습니다.

1. 글 게시를 위한 엔티티 및 리포지토리 작성

먼저, Post 엔티티와 이를 위한 JPA 리포지토리를 생성합니다.


    import javax.persistence.*;
    import java.time.LocalDateTime;

    @Entity
    public class Post {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        
        private String title;
        private String content;

        @ManyToOne
        @JoinColumn(name="user_id")
        private User user; // 작성자 정보

        private LocalDateTime createdAt;
        private LocalDateTime updatedAt;

        // getters and setters
    }
    

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

    public interface PostRepository extends JpaRepository {
    }
    

2. 글 작성 및 수정 기능 구현

컨트롤러를 작성하여 글 작성 및 수정 기능을 처리합니다.


    import org.springframework.security.core.annotation.AuthenticationPrincipal;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;

    @Controller
    @RequestMapping("/posts")
    public class PostController {

        private final PostRepository postRepository;

        public PostController(PostRepository postRepository) {
            this.postRepository = postRepository;
        }

        @GetMapping("/new")
        public String newPost(Model model) {
            model.addAttribute("post", new Post());
            return "newpost"; // 글 작성 페이지
        }

        @PostMapping
        public String createPost(@ModelAttribute Post post, @AuthenticationPrincipal User user) {
            post.setUser(user); // 현재 로그인한 사용자 설정
            post.setCreatedAt(LocalDateTime.now());
            postRepository.save(post);
            return "redirect:/posts";
        }

        @GetMapping("/{id}/edit")
        public String editPost(@PathVariable Long id, Model model) {
            Post post = postRepository.findById(id).orElseThrow();
            model.addAttribute("post", post);
            return "editpost"; // 글 수정 페이지
        }

        @PostMapping("/{id}")
        public String updatePost(@PathVariable Long id, @ModelAttribute Post post) {
            post.setId(id);
            post.setUpdatedAt(LocalDateTime.now());
            postRepository.save(post);
            return "redirect:/posts";
        }
    }
    

3. 글 삭제 기능 구현

글 삭제를 위한 메소드도 PostController에 추가합니다.


    @DeleteMapping("/{id}")
    public String deletePost(@PathVariable Long id) {
        postRepository.deleteById(id);
        return "redirect:/posts";
    }
    

글쓴이 확인 로직 추가

마지막으로, 글쓴이 확인 로직을 추가하여 사용자가 자신이 작성한 글만 수정 또는 삭제할 수 있도록 설정합니다. 이를 위해 사용자가 로그인했을 때, 해당 사용자의 정보와 글의 작성자를 비교하는 로직을 추가합니다.


    @PostMapping("/{id}/edit")
    public String editPost(@PathVariable Long id, @AuthenticationPrincipal User user) {
        Post post = postRepository.findById(id).orElseThrow();
        if (!post.getUser().equals(user)) {
            throw new AccessDeniedException("이 글은 수정할 수 없습니다."); // 접근 거부 예외
        }
        return "editpost"; // 수정 페이지로 이동
    }

    @DeleteMapping("/{id}")
    public String deletePost(@PathVariable Long id, @AuthenticationPrincipal User user) {
        Post post = postRepository.findById(id).orElseThrow();
        if (!post.getUser().equals(user)) {
            throw new AccessDeniedException("이 글은 삭제할 수 없습니다."); // 접근 거부 예외
        }
        postRepository.deleteById(id);
        return "redirect:/posts";
    }
    

결론

이번 강좌에서는 스프링 부트를 사용하여 OAuth2 기반의 로그인 및 로그아웃 기능을 구현하고, 글 작성, 수정, 삭제 기능을 추가하는 방법을 배웠습니다. 또한, 글쓴이 확인 로직을 통해 사용자가 자신의 글만 수정 또는 삭제할 수 있도록 하는 안전 장치를 마련했습니다. 이러한 과정을 통해 스프링 부트와 OAuth2의 기본적인 사용법을 익힐 수 있었으며, 실제 애플리케이션 개발에 필요한 기초 지식을 쌓을 수 있었습니다.

앞으로도 스프링 부트를 활용한 다양한 기능에 대해 학습하며, 더 나아가 실력이 향상되기를 바랍니다. 여러분의 개발 여정에 행운을 빕니다!