티스토리 뷰

반응형

SecurityFilterChain 커스터마이징과 URL 인증 예외 처리를 해보겠습니다.

 

기본 시큐리티 동작

Spring Security를 의존성에 추가하면 기본 동작은 다음과 같습니다.

  • 모든 요청 인증 필요
  • 기본 로그인 페이지(/login) 제공
  • 콘솔에 출력된 랜덤 패스워드로 로그인 가능 (username은 user)
     

하지만 실무에서는 일부 URL은 인증 없이 접근 가능하도록 해야 합니다.

예) /, /css/**, /js/**, /images/**, /public/** 등 정적 리소스

 

특정 요청 인증 예외 처리

📂 파일명: SecurityConfig.java

package com.example.security;


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.web.SecurityFilterChain;


@Configuration // 이 클래스가 스프링의 설정 클래스임을 명시
public class SecurityConfig {


    @Bean // SecurityFilterChain을 Bean으로 등록 (Spring Security 6 방식)
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // ✅ URL별 접근 권한을 설정하는 구간
            .authorizeHttpRequests(auth -> auth
                // requestMatchers(): 특정 경로에 대한 접근 권한 지정
                .requestMatchers("/", "/public/**", "/css/**", "/js/**", "/images/**").permitAll()
                // permitAll(): 인증 없이 누구나 접근 가능
                .anyRequest().authenticated() // 그 외 모든 요청은 인증 필요
            )


            // ✅ 폼 로그인 설정
            .formLogin(form -> form
                // loginPage(): 커스텀 로그인 페이지 경로 지정
                .loginPage("/login")
                // permitAll(): 로그인 페이지 접근은 인증 없이 허용
                .permitAll()
            )


            // ✅ 로그아웃 설정
            .logout(logout -> logout
                // logoutUrl(): 로그아웃 요청 URL 지정
                .logoutUrl("/logout")
                // permitAll(): 로그아웃 요청은 누구나 가능
                .permitAll()
            )


            // ✅ CSRF 설정
            // 기본적으로 CSRF가 활성화되어 POST/PUT/DELETE 요청 시 토큰 필요
            // 개발·테스트 단계에서는 편의상 비활성화 가능
            .csrf(csrf -> csrf.disable());


        // http.build(): 설정된 SecurityFilterChain 객체를 반환
        return http.build();
    }
}

 

📌 주요 메서드 정리

메서드 역할
authorizeHttpRequests() 요청 URL에 따라 인증/인가 규칙을 정의
requestMatchers() 특정 패턴의 URL을 선택
permitAll() 해당 URL은 인증 없이 접근 가능
authenticated() 해당 URL은 인증된 사용자만 접근 가능
formLogin() 폼 기반 로그인 기능 활성화
loginPage() 커스텀 로그인 페이지 경로 지정
logout() 로그아웃 기능 활성화 및 설정
logoutUrl() 로그아웃 요청 경로 지정
csrf().disable() CSRF 보호 비활성화 (개발용)
build() SecurityFilterChain 객체 생성

 

💡 이렇게 설정하면, 예를 들어 /admin에 접근하려고 하면 로그인하지 않은 경우 /login으로 리다이렉트되고,
정적 리소스(/css/** 등)는 로그인 없이 접근이 가능합니다.

 

커스텀 로그인 페이지 만들기

 

📂 파일명: LoginController.java

package com.example.security;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class LoginController {
	// 로그인 페이지 매핑
    @GetMapping("/login")
    public String loginPage() {
        return "login"; // templates/login.html
    }
}

 

📂 파일명: src/main/resources/templates/login.html

<!DOCTYPE html>

<head>
    <meta charset="UTF-8">
    <title>로그인</title>
</head>
<body>
<h2>로그인 페이지</h2>
<form th:action="@{/login}" method="post">
    <div>
        <label>아이디: <input type="text" name="username"></label>
    </div>
    <div>
        <label>비밀번호: <input type="password" name="password"></label>
    </div>
    <div>
        <button type="submit">로그인</button>
    </div>
</form>
</body>
</html>

 

의존성 설정

📌 Maven

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

 

📌 Gradle (Groovy)

implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

 

📌 Gradle (Kotlin DSL)

implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")

 

💡 이렇게 하면 /, /public/** 등은 로그인 없이 접근 가능하고,

다른 페이지에 접근하려 하면 /login 페이지로 리다이렉트됩니다.

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함