ssjune 2023. 5. 20. 00:11

책의 9. 로그아웃 처리의 설명

SecurityConfig.java

package com.mysite.config;

import java.io.IOException;
import java.nio.file.AccessDeniedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
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.WebSecurityConfiguration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.DigestAuthenticationFilter;
import com.mysite.common.security.CustomAccessDeniedHandler;
import com.mysite.common.security.CustomLoginSuccessHandler;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfig {

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		log.info("security config...");
		
		//URI 패턴으로 접근 제한을 설정한다.
		http.authorizeHttpRequests((authorize) -> authorize
				.requestMatchers("/board/list")
				.permitAll());
		http.authorizeHttpRequests((authorize) -> authorize
				.requestMatchers("/board/register")
				.hasRole("MEMBER"));
		http.authorizeHttpRequests((authorize) -> authorize
				.requestMatchers("/notice/list")
				.permitAll());
		http.authorizeHttpRequests((authorize) -> authorize
				.requestMatchers("/notice/register")
				.hasRole("ADMIN"));
		
		//사용자가 직접 정의한 로그인 페이지의 URI를 지정한다.
		http.formLogin()
			.loginPage("/login")
			.permitAll()
			.successHandler(authenticationSuccessHandler());
		
		//접근 거부 처리자의 URI 지정
		http.authorizeHttpRequests((authorize) -> authorize
				// Allow access to the "/accessError" page
				.requestMatchers("/accessError").permitAll() 
	            .anyRequest().authenticated()
	        )
	        .exceptionHandling((except) -> except
	            .accessDeniedHandler(accessDeniedHandler())
	        );
		//로그아웃 처리를 위한 URI를 지정하고, 로그아웃 후에 세션을 무효화한다.
		http.logout().logoutUrl("/logout").invalidateHttpSession(true);
		
		return http.build();
		
	}
	
	@Bean
	public AccessDeniedHandler accessDeniedHandler() {
		return new CustomAccessDeniedHandler();
	}
	
	@Bean
	public AuthenticationSuccessHandler authenticationSuccessHandler() {
		return new CustomLoginSuccessHandler();
	}
	
	@Bean
	public UserDetailsService users() {
		UserDetails user = User.builder()
			.username("member")
			.password("{noop}1234")
			.roles("MEMBER")
			.build();
		UserDetails admin = User.builder()
			.username("admin")
			.password("{noop}1234")
			.roles("ADMIN")
			.build();
		return new InMemoryUserDetailsManager(user, admin);
	}
}
반응형