Back-end/Spring

[Spring] 시큐리티 Security Form Login 인증 기본 설정 (스프링 3.0 버전 이상, 시큐리티 6.0 버전 이상, WebSecurityConfigurerAdapter 대체)

shoney9254 2024. 1. 10. 13:56
반응형

websecurityconfigureradapter 대체되는 방식으로 form login을 사용하는 기본 예제를 알려드립니다.

스프링 3.0 이상 버전은 스프링 시큐리티 6.0 버전 이상만 사용가능하게 되면서, 기존의 방식으로는 사용불가능합니다. 

스프링 3.0 버전 이상부터는 websecurityconfigureradapter deprecated 됨에 따라서,

@Bean을 사용하고 SecurityFilterChain를 리턴하는 함수로 사용해야합니다. 

해당 함수는 아래 예제들에서 자세히 설명드리겠습니다.

 

1. Form Login 인증

아래 예제를 통해서 어떻게 동작하는지 살펴보도록 하겠습니다.

 

1-1. formLogin 기본적인 내용 입력하기

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeHttpRequests(ar -> ar
                        .anyRequest()
                        .authenticated()
                )
                .formLogin(form -> form
                        .loginPage("/loginPage")
                        .defaultSuccessUrl("/members")
                        .failureUrl("/login.html?error=true")
                        .usernameParameter("userid")
                        .passwordParameter("passwd")
                        .loginProcessingUrl("/login_page")
                        .permitAll()
                )
                .build();
    }

- loginPage : 로그인 화면의 url을 설정합니다. (시작 화면으로 지정됩니다.

- defaultSuccessUrl : 로그인이 성공할 경우, 이동하게 되는 디폴트 url을 지정할 수 있습니다.

- failureUrl : 실패시 이동하는 url 설정

- usernameParameter : 웹의 username의 파라이름을 설정 (아래 캡처 참조)

- passwordParameter : 웹의 password의 파라이름을 설정 (아래 캡처 참조)

- loginProcessingUrl : 웹 로그인창의 action 설정 (아래 캡처 참조)

 

 

 

1-2. 핸들러 사용하는 방법

성공 또는 실패할 경우 핸들러를 사용해서 원하는 것들을 실행할 수 있습니다.

아래 예제를 통해서 확인해봅시다.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
            .authorizeHttpRequests(ar -> ar
                    .anyRequest()
                    .authenticated()
            )
            .formLogin(form -> form
                    .loginPage("/loginPage")
                    .defaultSuccessUrl("/members")
                    .failureUrl("/login.html?error=true")
                    .usernameParameter("userid")
                    .passwordParameter("passwd")
                    .loginProcessingUrl("/login_page")
                    .successHandler(new AuthenticationSuccessHandler() {
                        @Override
                        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                            System.out.println("authentication :" + authentication.getName());
                            response.sendRedirect("/");
                        }
                    })
                    .failureHandler(new AuthenticationFailureHandler() {
                        @Override
                        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                            System.out.println("exception :" + exception.getMessage());
                            response.sendRedirect("/login");
                        }
                    })
                    .permitAll()
            )
            .build();
}

1-1 에서 사용했던 내용과 핸들러가 같이 사용되는 경우는 핸들러의 소스코드를 우선순위가 높게 실행됩니다.

- successHandler : AuthenticationSuccessHandler로 익명 메서드를 만들어서 사용했습니다. response.sendRedirect를 통해서 성공 시 이동하는 url를 입력할 수 있습니다.

- failureHandler : AuthenticationFailureHandler로 익명 메서드를 만들어서 사용했습니다.response.sendRedirect를 통해서 성공 시 이동하는 url를 입력할 수 있습니다.

 

핸들러 실행결과 로그

- successHandler

- failureHandler

 

 

 

 

반응형