"꾸준하고 완벽한 한 걸음"

Spring/Spring Security

개발자 유미 - 스프링 시큐리티 4. 커스텀 로그인 설정

kimyoungrok 2025. 3. 7. 01:38
728x90

스프링 시큐리티 4 : 커스텀 로그인 설정

 

개발자 유미 | 커뮤니티

 

개발자 유미 | 커뮤니티

 

www.devyummi.com

 


기존의 Config 설정을 다시 확인해보자.

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((auth)->auth
                        .requestMatchers("/", "/login").permitAll()
                        .requestMatchers("/admin").hasRole("ADMIN")
                        .requestMatchers("/my/**").hasAnyRole("ADMIN", "USER")
                        .anyRequest().authenticated()
                );
        return http.build();
    }

.requestMatchers("/", "/login").permitAll() 에 의해 / 또는 /login 의 접근은 허용되어 있다.

이외의 /admin , /my/** 에 대해서는 권한이 있는 경우에만 접근이 가능한데, 접근 권한 확인을 위해 로그인 페이지로 리디렉션 되는 것이 아닌, 오류 페이지가 뜬다.

login.mustache 생성

로그인 화면을 구성해줍니다.

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    login page
    <hr>
    <form action="/loginProc" method="post" name="loginForm">
        <input id="username" type="text" name="username" placeholder="id"/>
        <input id="password" type="password" name="password" placeholder="password"/>
        <input type="submit" value="login"/>
    </form>
</body>
</html>

LoginController.java 생성

로그인 화면으로 이동하기 위한 컨트롤러를 생성합니다.

package com.example.testsecurity.controller;

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

@Controller
public class LoginController {
    @GetMapping("/login")
    public String loginP() {

        return "login";
    }
}

로그인 페이지 리디렉션 설정

이제 권한이 필요한 경로에 접근시 로그인 페이지로 리디렉션을 설정합니다.

package com.example.testsecurity.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.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((auth)->auth
                        .requestMatchers("/", "/login").permitAll()
                        .requestMatchers("/admin").hasRole("ADMIN")
                        .requestMatchers("/my/**").hasAnyRole("ADMIN", "USER")
                        .anyRequest().authenticated()
                );
        http
                .formLogin((auth) -> auth.loginPage("/login")
                        .loginProcessingUrl("/loginProc")
                        .permitAll()
                );

        http
                .csrf((auth) -> auth.disable());
        return http.build();
    }
}
  • loginPage("/login")
  • 커스텀 로그인 페이지를 /login 경로에 설정합니다.
  • loginProcessingUrl("/loginProc")
  • 로그인 폼에서 제출된 데이터를 처리할 경로를 /loginProc로 설정합니다. 이 경로로 사용자 이름과 비밀번호가 전송되며, Spring Security가 인증을 처리합니다.
  • http.csrf((auth) -> auth.disable())
  • CSRF(Cross-Site Request Forgery, 사이트 간 요청 위조) 보호 기능을 비활성화합니다. 이 기능을 비활성화하는 것은 주로 API 기반 애플리케이션에서 사용되지만, 일반적인 웹 애플리케이션에서는 CSRF 보호 기능을 활성화하는 것이 권장됩니다.

이제 /admin , /my/** 로 이동시 /login 으로 리디렉션 되는 것을 확인할 수 있다.

728x90