스프링부트

JWT 토큰을 이용한 로그인 구현 - 1

하이자바 2025. 4. 16. 19:40

JWT를 이용해 로그인을 구현하고자 한다.

토큰의 경우는 액세스, 리프레시를 나누지 않고 하나의 토큰만 사용하여 구현한다.

 

세팅은 자바 17, 나머지는 최신 버전으로 프로젝트를 생성한다.

필요한 의존성 Lombok, Security, Spring Web, Mysql, JPA 총 5개이다.

그리고 추가적으로 그래들에 JWT 의존성을 추가해준다. (최신버전으로 추가하였음, 0.11.5 버전 기준 사용 방식 차이가 있음)

implementation 'io.jsonwebtoken:jjwt-api:0.12.6'
implementation 'io.jsonwebtoken:jjwt-impl:0.12.6'
runtimeOnly 'io.jsonwebtoken:jjwt-gson:0.12.6'

 

다음으로 시큐리티 콘피규 추가

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 세션은 csrf 방어해야하지만 토큰은 필요없음
        http.csrf(AbstractHttpConfigurer::disable);
        http.formLogin(AbstractHttpConfigurer::disable);
        http.httpBasic(AbstractHttpConfigurer::disable);

        // 인가
        http.authorizeHttpRequests((auth) -> auth
                .requestMatchers("/login", "/", "/join").permitAll()
                .requestMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated());

        // 토큰 방식 세션 사용하지 않음
        http.sessionManagement((session) -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        return http.build();
    }
    @Bean
    public BCryptPasswordEncoder bcryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

 

다음으론 DB 연결 및 JPA 설정이다.

다음과 같이 application.properties 작성

spring.datasource.url=jdbc:mysql://localhost:3306/jwt
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.open-in-view=false
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

 

유저 엔티티 작성

@Entity(name = "tb_user")
@Getter
@Setter
public class UserEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(nullable = false, length = 30)
    private String userName;
    @Column(nullable = false, length = 30)
    private String password;
    @Column(nullable = false, length = 10)
    private String role;
}

 

그리고 3 Layer Architecture 클래스들을 작성해주면 된다.

다음 글로는 로그인에 대한 로직 서비스 관련 글을 작성하고자 한다.