8. 로그인 성공 처리

책의 8. 로그인 성공 처리의 설명

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
				.requestMatchers("/accessError").permitAll() // Allow access to the "/accessError" page
	            .anyRequest().authenticated()
	        )
	        .exceptionHandling((except) -> except
	            .accessDeniedHandler(accessDeniedHandler())
	        );
		
		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);
	}
}

CustomLoginSuccessHandler.java

package com.mysite.common.security;

import java.io.IOException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class CustomLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
		@Override
		public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
				Authentication auth) throws ServletException, IOException {
			log.info("onAuthenticationSuccess");
			User customUser = (User)auth.getPrincipal();
			
			log.info("username = " + customUser.getUsername());
			super.onAuthenticationSuccess(request, response, auth);
			
		}
		
}
반응형

댓글()