스프링 부트 백엔드 개발 강좌, OAuth2로 로그인 로그아웃 구현, OAuth2 설정 파일 작성하기

1. 서론

최근 마이크로서비스 아키텍처와 클라우드 서비스를 기반으로 한 웹 애플리케이션 개발이 증가함에 따라, 스프링 부트(Spring Boot)와 같은 프레임워크의 인기도 높아지고 있습니다.
스프링 부트는 복잡한 설정 없이도 애플리케이션을 신속하게 개발할 수 있도록 도와주는 프레임워크입니다.
이번 강좌에서는 스프링 부트를 이용한 백엔드 개발에서 OAuth2를 사용하여 로그인 및 로그아웃 기능을 구현하는 방법을 자세히 알아보겠습니다.

2. OAuth2란?

OAuth2는 사용자가 클라이언트 애플리케이션에 대한 접근 권한을 제어할 수 있도록 해주는 인증 프로토콜입니다.
OAuth2를 사용하면 사용자가 자신의 자격 증명을 애플리케이션과 공유하지 않고도 특정 자원에 대한 인증 및 인가를 수행할 수 있습니다.
이는 보안을 강화하고 사용자 경험을 크게 개선할 수 있는 방법입니다.

2.1 OAuth2의 주요 구성 요소

  • Resource Owner: 클라이언트 애플리케이션에 권한을 부여하는 사용자
  • Client: Resource Owner의 자원에 접근하려는 애플리케이션
  • Resource Server: 사용자의 자원이 저장된 서버
  • Authorization Server: 사용자의 인증 정보를 처리하고 클라이언트에게 토큰을 발급하는 서버

3. 스프링 부트 프로젝트 설정

스프링 부트 애플리케이션을 시작하기 위해 먼저 새로운 프로젝트를 생성합니다.
Spring Initializr를 사용하여 Maven 또는 Gradle 기반의 프로젝트를 생성할 수 있습니다.

3.1 의존성 추가

OAuth2 인증을 구현하기 위해, 다음 의존성을 추가해야 합니다:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.0.RELEASE'
}

3.2 application.properties 설정

다음으로, src/main/resources/application.properties 파일을 열어 OAuth2 인증에 필요한 설정을 추가합니다.
아래의 설정 예시를 참조하세요.


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

4. OAuth2 로그인 구현

이제 애플리케이션에서 OAuth2 로그인을 구현해 보겠습니다. 스프링 시큐리티(Spring Security)를 통해 간단하게 설정할 수 있습니다.

4.1 Security Configuration

새로운 Java 클래스를 생성하여 보안 설정을 구성합니다.

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

5. 사용자 프로필 조회

사용자가 로그인하면 OAuth2 서버로부터 사용자 정보를 요청하여 프로필을 받아올 수 있습니다.
이를 위한 컨트롤러를 작성합니다.

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserProfileController {
    @GetMapping("/user")
    public String user(@AuthenticationPrincipal OAuth2User principal, Model model) {
        model.addAttribute("name", principal.getAttribute("name"));
        model.addAttribute("email", principal.getAttribute("email"));
        return "userProfile";
    }
}

6. 로그아웃 구현

로그아웃 기능은 스프링 시큐리티에서 기본적으로 제공되며, 설정을 통해 손쉽게 구현할 수 있습니다.
아래와 같이 로그아웃 URL과 관련된 설정을 추가합니다.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/login**", "/error**").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .and()
            .logout()
                .logoutSuccessUrl("/")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID");
    }

7. 결론

본 강좌에서는 스프링 부트를 이용하여 OAuth2를 통해 로그인 및 로그아웃 기능을 구현하는 간단한 방법을 살펴보았습니다.
스프링 부트와 OAuth2를 사용하면 외부 인증 시스템과 쉽게 연동할 수 있으며, 이는 애플리케이션의 보안을 강화하고 사용자 경험을 개선하는 데에 크게 기여합니다.
앞으로 자신의 프로젝트에 OAuth2를 적용하여 보다 안전하고 편리한 서비스를 제공해 보세요!

8. 추가 자료

더 많은 정보를 원하시면 공식 문서와 기타 자료를 참조하시기 바랍니다.

스프링 부트 백엔드 개발 강좌, main 디렉터리 구성하기

스프링 부트(SPRING BOOT)는 자바 기반의 프레임워크로, 개발자가 복잡한 설정 없이도 쉽게 응용 프로그램을 구축할 수 있도록 돕는 도구입니다. 이 강좌에서는 스프링 부트 프로젝트의 main 디렉터리를 어떻게 구성할 것인지에 대한 내용을 다룰 것입니다. 이 디렉터리는 자바 애플리케이션의 시작점이자 중요한 비즈니스 로직을 구현하는 곳입니다.

스프링 부트 프로젝트 구조

스프링 부트 프로젝트는 미리 정의된 구조를 따릅니다. IDE에서 스프링 부트 프로젝트를 생성하면 다음과 같은 기본 구조가 만들어집니다.

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── demo
│   │               ├── DemoApplication.java
│   │               └── controller
│   │               └── service
│   │               └── repository
│   └── resources
│       ├── application.properties
│       └── static
│       └── templates
└── test
    └── java

1. src/main/java 디렉터리

src/main/java 디렉터리는 실제 자바 소스 코드가 위치하는 장소로, 각 패키지와 클래스 파일이 이곳에 보관됩니다. 스프링 부트에서는 일반적으로 com.example.demo와 같은 형식으로 패키지를 구성합니다.

1.1 주 애플리케이션 클래스

DemoApplication.java 파일은 스프링 부트 애플리케이션의 시작점입니다. 이 클래스는 @SpringBootApplication 애너테이션이 부여되며, 이 애너테이션은 다음과 같은 3가지 기능을 포함합니다:

  • @Configuration: 자바 기반의 구성 클래스입니다.
  • @EnableAutoConfiguration: 스프링 부트의 자동 설정 기능을 활성화합니다.
  • @ComponentScan: 지정한 패키지를 탐색하여 스프링 컴포넌트를 자동으로 검색합니다.

아래는 주 애플리케이션 클래스의 예시입니다.

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

1.2 패키지 구조

소스 파일이 많은 경우, 적절한 패키지 구조를 정의하는 것이 중요합니다. 일반적으로 controller, service, repository와 같은 패키지를 정의합니다.

Controller 패키지

controller 패키지는 요청을 처리하고 응답을 반환하는 메소드를 포함합니다. RESTful API에서는 주로 @RestController 어노테이션을 사용하여 REST API 서버를 구성합니다.

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}

Service 패키지

service 패키지는 비즈니스 로직을 처리하는 클래스를 포함합니다. 이곳의 클래스는 @Service 애너테이션을 사용하여 스프링 컨텍스트에 등록됩니다.

package com.example.demo.service;

import org.springframework.stereotype.Service;

@Service
public class HelloService {
    public String getGreeting() {
        return "Hello from Service!";
    }
}

Repository 패키지

repository 패키지는 데이터베이스와의 상호작용을 맡습니다. 보통 JpaRepository를 상속받아 CRUD 기능을 제공합니다.

package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.User;

@Repository
public interface UserRepository extends JpaRepository {
}

2. src/main/resources 디렉터리

src/main/resources 디렉터리는 애플리케이션에서 사용하는 정적 파일, 템플릿, 설정 파일 등이 위치하는 곳입니다. 이곳의 주요 파일 및 디렉터리는 다음과 같습니다.

2.1 application.properties

설정 파일인 application.properties는 애플리케이션의 환경 설정을 담당합니다. 데이터베이스 설정, 포트 번호, 로그 레벨 등을 여기서 설정할 수 있습니다.

spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=password
server.port=8080
logging.level.org.springframework=DEBUG

2.2 static 디렉터리

static 디렉터리는 CSS, JavaScript, 이미지 파일 등 정적 리소스를 보관하는 곳입니다. 스프링 부트는 이 디렉터리의 모든 파일을 자동으로 서빙합니다.

2.3 templates 디렉터리

templates 디렉터리는 Thymeleaf와 같은 템플릿 엔진을 사용하여 동적으로 HTML 파일을 생성하는 데 사용됩니다. 여기서는 HTML 파일을 만들고 동적인 데이터를 주입할 수 있습니다.





    Welcome


    

Welcome Message

3. src/test/java 디렉터리

src/test/java 디렉터리는 애플리케이션의 테스트 관련 소스를 포함합니다. JUnit이나 Mockito와 같은 테스트 프레임워크를 사용하여 유닛 테스트와 통합 테스트를 수행합니다.

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class DemoApplicationTests {
    
    @Autowired
    private HelloService helloService;

    @Test
    void contextLoads() {
        assertNotNull(helloService);
    }
}

결론

이번 강좌에서는 스프링 부트 프로젝트의 main 디렉터리의 구성 방법에 대해 자세히 알아보았습니다. 프로젝트 구조를 이해하고 올바르게 구성함으로써, 개발자는 더 효율적이고 관리 가능한 코드를 작성할 수 있습니다. 이 구조는 앞으로의 유지보수와 협업에서 큰 도움이 될 것입니다. 성공적인 스프링 부트 백엔드 개발을 기원합니다.

스프링 부트 백엔드 개발 강좌, NoSQL이란

최근 몇 년간 소프트웨어 개발의 패러다임은 크게 변화해왔습니다. 특히 데이터의 양이 폭발적으로 증가하면서 데이터베이스 관리 방법에도 새로운 방식이 필요해졌습니다. 전통적인 관계형 데이터베이스가 여전히 널리 사용되고 있지만, NoSQL 데이터베이스가 부각되면서 새로운 트렌드가 형성되고 있습니다. 본 글에서는 스프링 부트 백엔드 개발에서 NoSQL이 무엇인지, 언제 사용해야 하는지, 그리고 NoSQL 데이터베이스의 종류와 특징에 대해 자세히 설명하겠습니다.

NoSQL의 개념

NoSQL은 “Not Only SQL”의 약자로, 기존의 관계형 데이터베이스 관리 시스템(RDBMS)에 대한 대안으로 개발된 데이터 저장 모델을 가리킵니다. NoSQL은 다양한 데이터 모델을 지원하여 관계형 데이터베이스가 처리가 어려운 대량의 비정형 데이터나 반정형 데이터를 유연하게 저장하고 쿼리할 수 있는 기능을 제공합니다.

NoSQL의 주요 특징은 다음과 같습니다:

  • 스키마 유연성: NoSQL 데이터베이스는 고정된 스키마를 가지지 않으며, 데이터 구조가 변경되어도 쉬운 적응이 가능합니다.
  • 수평적 확장성: 데이터의 양이 증가할 때 클러스터에 서버를 추가하여 수평적으로 확장할 수 있습니다.
  • 고가용성: 장애가 발생해도 높은 가용성을 유지하기 위해 복제 및 분산 저장 기능을 제공합니다.

NoSQL의 필요성

NoSQL이 필요한 이유는 주로 다음과 같습니다.

  • 대량의 데이터 처리: IoT, 소셜 미디어, 로그 데이터 등 대규모 데이터 수집 및 저장이 필요할 때 유용합니다.
  • 비정형 데이터: 관계형 데이터베이스는 정형 데이터에 최적화되어 있지만, 이미지, 비디오 및 다양한 형식의 데이터를 저장해야 할 경우 NoSQL이 적합합니다.
  • 빠른 개발: 동적인 데이터 구조에 대한 적응을 빠르게 할 수 있어 애플리케이션의 개발 속도가 향상됩니다.

NoSQL 데이터베이스의 종류

NoSQL 데이터베이스는 여러 가지 유형으로 분류되며, 각 유형은 그 특성에 따라 특정 용례에 적합합니다.

1. 키-값 저장소

키-값 저장소는 데이터가 키와 값 쌍으로 저장되는 구조입니다. 간단한 구조와 빠른 조회 속도를 제공하여 세션 관리, 캐싱 및 간단한 데이터 저장에 적합합니다. 예를 들면 Redis와 DynamoDB가 있습니다.

2. 문서 저장소

문서 저장소는 JSON, BSON 및 XML과 같은 문서 형식으로 데이터를 저장합니다. 데이터의 스키마가 유연하여, 해당 문서 내에서 다른 구조의 데이터를 저장할 수 있는 장점이 있습니다. MongoDB와 CouchDB가 대표적입니다.

3. 열 지향 저장소

열 지향 저장소는 데이터를 열(column) 단위로 저장하여 대량의 데이터 처리에 최적화되어 있습니다. 자주 사용되는 열을 메모리에 유지함으로써 성능을 향상시킬 수 있습니다. 대표적으로 Apache Cassandra와 HBase가 있습니다.

4. 그래프 데이터베이스

그래프 데이터베이스는 노드와 엣지로 표현된 데이터를 저장합니다. 관계의 중요성이 큰 데이터 모델에 적합하며, 소셜 네트워크 분석 등에서 많이 사용됩니다. Neo4j가 잘 알려져 있습니다.

스프링 부트와 NoSQL 연동

스프링 부트는 NoSQL 데이터베이스와의 통합을 위해 다양한 스프링 데이터 프로젝트를 지원합니다. 이 섹션에서는 스프링 부트를 사용하여 MongoDB와의 간단한 통합 예제를 살펴보겠습니다.

1. 의존성 추가

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
    

2. MongoDB 설정

application.properties 파일에 MongoDB와의 연결 설정을 추가합니다.

        spring.data.mongodb.uri=mongodb://localhost:27017/testdb
    

3. 도메인 클래스 생성

    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;

    @Document(collection = "user")
    public class User {
        @Id
        private String id;
        private String name;
        private String email;

        // getters and setters
    }
    

4. 리포지토리 생성

    import org.springframework.data.mongodb.repository.MongoRepository;

    public interface UserRepository extends MongoRepository<User, String> {
        User findByName(String name);
    }
    

5. 서비스 및 컨트롤러 생성

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import java.util.List;

    @Service
    public class UserService {
        @Autowired
        private UserRepository userRepository;

        public List<User> getAllUsers() {
            return userRepository.findAll();
        }

        public User getUserByName(String name) {
            return userRepository.findByName(name);
        }
        
        public void createUser(User user) {
            userRepository.save(user);
        }
    }
    

결론

NoSQL 데이터베이스는 현대 웹 애플리케이션에서 중요한 역할을 하며, 개발자들이 다양한 데이터 처리 요구를 충족할 수 있도록 돕습니다. 스프링 부트와 함께 사용함으로써 더 높은 생산성과 유연성을 제공하며, 특히 비정형 데이터 환경에서 그 가치를 발휘할 수 있습니다. 본 강좌를 통해 NoSQL의 본질과 스프링 부트에서의 실용적인 활용 사례를 정리할 수 있기를 바랍니다.

스프링 부트 백엔드 개발 강좌, JWT로 로그인 로그아웃 구현, 토큰 제공자 추가하기

1. 서론

최근 마이크로서비스 아키텍처와 RESTful API의 발전으로 인해 백엔드 개발의 중요성이 더욱 부각되고 있습니다. 오늘 강좌에서는 스프링 부트를 이용한 백엔드 개발을 통해 JSON Web Token(JWT)을 사용하여 사용자 인증을 구현하는 방법에 대해 알아보겠습니다. 이 강좌는 로그인 및 로그아웃 기능을 포함한 JWT 기반의 토큰 제공자를 추가하는 것에 중점을 두고 있습니다.

2. 스프링 부트란?

스프링 부트는 스프링 프레임워크를 기반으로 하여 빠르고 쉽게 스프링 애플리케이션을 개발할 수 있도록 돕는 도구입니다. 복잡한 XML 설정 없이 데모 및 실제 애플리케이션을 손쉽게 개발할 수 있게 해줍니다. 또한, 스프링 부트는 내장형 서버를 지원하여 외부 서버에 배포하지 않고도 로컬에서 애플리케이션을 실행할 수 있습니다.

3. JWT의 이해

JSON Web Token(JWT)은 데이터 전송을 위한 개방형 표준으로, 클라이언트와 서버 간에 안전하게 정보를 전송하는 데 사용됩니다. JWT는 주로 인증 및 정보 교환에 사용됩니다. JWT는 세 부분으로 구성됩니다:

  • Header (헤더): 토큰의 유형과 암호화 알고리즘을 정의합니다.
  • Payload (페이로드): 사용자 정보를 저장하는 부분으로, 사용자 ID와 같은 정보가 포함됩니다.
  • Signature (서명): 헤더와 페이로드를 조합하여 비밀 키로 서명한 부분입니다.

4. 스프링 부트 프로젝트 설정

우선, 스프링 부트 프로젝트를 설정해야 합니다. Spring Initializr 웹사이트를 방문하여 새 프로젝트를 생성합니다. 다음의 종속성을 추가해야 합니다:

  • Spring Web
  • Spring Security
  • Spring Data JPA
  • H2 Database (또는 원하는 데이터베이스)
  • jjwt (JWT 사용을 위한 라이브러리)

5. 사용자의 엔티티 클래스 생성

사용자 정보를 저장하기 위한 엔티티 클래스를 생성합니다. 다음은 User 엔티티 클래스의 예입니다:


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

    @Column(unique = true)
    private String username;

    private String password;

    // Getter and Setter methods
}

            

6. JWT 유틸리티 클래스 작성

JWT를 생성하고 검증하기 위한 유틸리티 클래스를 작성합니다.


@Component
public class JwtUtil {
    private String secretKey = "mySecretKey"; // 비밀 키

    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + 10 * 60 * 1000)) // 만료 시간 설정
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }

    public boolean validateToken(String token, String username) {
        final String extractedUsername = extractUsername(token);
        return (extractedUsername.equals(username) && !isTokenExpired(token));
    }

    public String extractUsername(String token) {
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
    }

    private boolean isTokenExpired(String token) {
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getExpiration().before(new Date());
    }
}

            

7. 스프링 시큐리티 설정

Spring Security를 설정하여 JWT 기반의 인증 프로세스를 구현합니다. 먼저, SecurityFilterChain을 설정합니다.


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests().antMatchers("/authenticate").permitAll()
            .anyRequest().authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("password")).roles("USER");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

            

8. JWT 요청 필터 작성

사용자 요청에서 JWT를 필터링하여 인증 여부를 확인하는 JWT Request Filter를 작성합니다.


@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 명시된 사용자 인증 처리
        }
        chain.doFilter(request, response);
    }
}

            

9. 로그인 및 토큰 생성 컨트롤러 작성

사용자의 로그인 요청을 처리하고, JWT를 생성하는 컨트롤러를 작성합니다.


@RestController
public class AuthController {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/authenticate")
    public ResponseEntity authenticate(@RequestBody AuthRequest authRequest) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword()));
        } catch (BadCredentialsException e) {
            throw new Exception("잘못된 사용자 이름 또는 비밀번호", e);
        }

        final String jwt = jwtUtil.generateToken(authRequest.getUsername());
        return ResponseEntity.ok(new AuthResponse(jwt));
    }
}

            

10. 로그아웃 관리

JWT은 클라이언트 측에서 관리되기 때문에 로그아웃 기능은 클라이언트에서 토큰을 삭제하여 단순히 수행할 수 있습니다. 하지만, 서버 측에서 로그아웃을 구현하는 방법도 있습니다. 예를 들어, 블랙리스트를 유지하여 만료되기 전에 로그아웃된 토큰을 차단할 수 있습니다.

11. 미들웨어 구성

미들웨어를 사용하여 요청을 전처리하고 후처리하는 기능을 추가할 수 있습니다. 예를 들어, 모든 요청에 대해 JWT를 검사하거나, 특정 엔드포인트에 대한 접근을 제한할 수 있습니다.

12. 테스트와 디버깅

상당한 수준의 테스트를 적용하여 코드의 품질을 보장해야 합니다. 각 서비스, 컨트롤러 및 리포지토리에 대한 단위 테스트를 작성합니다. 스프링 부트는 Junit과 Mockito를 통해 효과적인 테스트 환경을 제공합니다.

13. 결론

이 강좌에서는 스프링 부트와 JWT를 사용하는 로그인 및 로그아웃 구현 방법에 대해 자세히 살펴보았습니다. JWT는 클라이언트와 서버 간의 통신을 안전하게 처리하는 좋은 방법이며, 이를 통해 웹 애플리케이션의 보안을 한층 강화할 수 있습니다. 이러한 방식으로 백엔드 개발에 대한 이해도를 높이고, 실제 프로젝트에서는 이러한 구현을 통해 사용자 인증 기능을 보다 효율적으로 관리할 수 있을 것입니다.

스프링 부트 백엔드 개발 강좌, JWT로 로그인 로그아웃 구현, 토큰 필터 구현하기

1. 서론

스프링 부트(Spring Boot)는 Java 기반 웹 애플리케이션을 손쉽게 개발할 수 있도록 도와주는 프레임워크입니다. 최근 들어 웹 애플리케이션에 대한 수요가 급증하면서, 보안 및 인증에 대한 이해가 중요해졌습니다. 이 강좌에서는 JSON Web Token(JWT)을 사용하여 로그인 및 로그아웃 기능을 구현하고, 필터를 통해 JWT 토큰을 검증하는 방법을 알아보겠습니다. 이 과정에서 스프링 부트의 다양한 기능을 활용하여 더 안전하고 효율적인 백엔드 애플리케이션을 구축하는 법을 배우게 될 것입니다.

2. JWT란 무엇인가?

JSON Web Token(JWT)은 두 개의 엔티티 간에 정보를 안전하게 전송하기 위해 사용하는 JSON 기반의 오브젝트입니다. JWT는 사용자 인증뿐만 아니라, 클레임 기반의 정보 전송을 위한 표준으로 자리 잡고 있습니다. JWT는 다음과 같이 세 가지 구성 요소로 나뉩니다:

  • 헤더(Header): JWT의 타입과 해싱 알고리즘을 정의합니다.
  • 페이로드(Payload): 전송하려는 클레임 정보가 포함됩니다.
  • 서명(Signature): 헤더와 페이로드를 결합한 후 비밀 키를 사용하여 생성됩니다. 이를 통해 JWT의 무결성을 확인할 수 있습니다.

3. 스프링 부트 프로젝트 설정하기

스프링 부트 프로젝트를 시작하려면 기본적인 설정부터 해야 합니다. 이러한 설정을 위해 스프링 이니셜라이저(Spring Initializr)를 이용할 수 있습니다. 프로젝트 생성 시 선택해야 할 사항은 다음과 같습니다:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Stable version (Latest)
  • Dependencies: Spring Web, Spring Security, Spring Data JPA, Spring Boot DevTools, H2 Database

프로젝트가 생성되면 IDE에서 열고, 필요한 의존성을 추가할 수 있습니다.

4. 엔티티 클래스 및 리포지토리 생성하기

우선 유저(User) 엔티티를 정의해야 합니다. 간단한 User 엔티티는 사용자 정보를 저장하는 클래스입니다. 이를 통해 우리는 데이터베이스와 상호작용할 수 있습니다.

package com.example.demo.entity;

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 username;
    private String password;
    
    // Getters and Setters
}

리포지토리는 엔티티와 데이터베이스의 CRUD 작업을 수행하는 데 필요합니다.

package com.example.demo.repository;

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

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

5. 서비스 클래스 생성하기

비즈니스 로직을 처리하는 서비스 클래스가 필요합니다. 이 클래스에서는 사용자 등록, 로그인 등의 기능을 구현합니다.

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    
    public User register(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }
    
    public User findUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }
}

6. 보안 설정 및 JWT 생성하기

스프링 시큐리티를 사용하여 애플리케이션의 보안을 강화할 수 있습니다. 이를 위해 SecurityConfig 클래스를 생성하고, JWT 토큰을 생성하는 클래스를 추가해야 합니다.

package com.example.demo.config;

import com.example.demo.security.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.config.annotation.web.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/auth/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

7. JWT 생성 및 검증 구현하기

로그인 시 사용자의 정보를 바탕으로 JWT를 생성하여 클라이언트에 전달합니다. 이를 위해 JWT 유틸리티 클래스를 생성하여 토큰 생성 및 검증 작업을 수행합니다.

package com.example.demo.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {
    
    private final String SECRET_KEY = "secret_key";
    private final long EXPIRATION_TIME = 86400000; // 1 day

    public String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        return createToken(claims, username);
    }

    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public boolean validateToken(String token, String username) {
        final String extractedUsername = extractUsername(token);
        return (extractedUsername.equals(username) && !isTokenExpired(token));
    }

    private boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    private Date extractExpiration(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getExpiration();
    }

    public String extractUsername(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject();
    }
}

8. 로그인 및 로그아웃 기능 구현하기

이제 사용자가 로그인하면 JWT를 발급받고, 로그아웃 시에는 클라이언트가 토큰을 삭제하는 방식으로 구현합니다. 아래는 로그인 API의 예시입니다.

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.security.JwtUtil;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody User user) {
        User foundUser = userService.findUserByUsername(user.getUsername());
        if (foundUser != null && passwordEncoder.matches(user.getPassword(), foundUser.getPassword())) {
            return ResponseEntity.ok(jwtUtil.generateToken(foundUser.getUsername()));
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
    }

    @PostMapping("/logout")
    public ResponseEntity<String> logout() {
        // 로그아웃 기능은 클라이언트 측에서 구현하도록 합니다.
        return ResponseEntity.ok("Successfully logged out.");
    }
}

9. JWT 필터 구현하기

JWT 필터를 구현하여 모든 요청에서 JWT를 검증하고, 인증을 처리하는 과정이 필요합니다. 이를 위해 JwtAuthenticationFilter 클래스를 생성합니다.

package com.example.demo.security;

import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            try {
                username = jwtUtil.extractUsername(jwt);
            } catch (ExpiredJwtException e) {
                System.out.println("JWT is expired");
            }

            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                if (jwtUtil.validateToken(jwt, userDetails.getUsername())) {
                    UsernamePasswordAuthenticationToken authenticationToken = 
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}

10. 결론

이번 강좌에서는 스프링 부트를 이용하여 JWT를 통한 로그인 및 로그아웃 기능을 구현하는 방법을 배웠습니다. 우리는 JWT 토큰을 생성하고 검증하는 방법, 그리고 스프링 시큐리티를 활용하여 애플리케이션의 보안을 강화하는 방법에 대해서도 알아보았습니다. 이 과정을 통해 백엔드 애플리케이션의 인증 및 권한 관리를 더 안전하게 처리할 수 있는 기반을 마련할 수 있습니다. 더불어, 스프링 부트의 다양한 기능을 활용하여 효율적이고 안전한 웹 애플리케이션 개발을 실현할 수 있을 것입니다.

11. 참고 자료