14. 자동 로그인

책의 14. 자동 로그인 의 내용

SecurityConfig.java

package com.mysite.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import com.mysite.common.security.CustomAccessDeniedHandler;
import com.mysite.common.security.CustomLoginSuccessHandler;
import lombok.extern.slf4j.Slf4j;

@Configuration
@Slf4j
public class SecurityConfig {
	
	@Autowired
	DataSource datasource;
	
	@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"));
		http.authorizeHttpRequests((auth)->auth
				.requestMatchers("/home")
				.permitAll());
		
		//사용자가 직접 정의한 로그인 페이지의 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);

		//데이터소스를 지정하고 테이블을 이용해서 기존 로그인 정보를 기록
		http.rememberMe()
			// 랜덤한 키 값
			.key("random")
			.tokenRepository(createJDBCRepository())
			//쿠키의 유효시간을 지정한다.
			.tokenValiditySeconds(60*60*24);	
		
		return http.build();
		
	}
	

	@Bean
	public AccessDeniedHandler accessDeniedHandler() {
		return new CustomAccessDeniedHandler();
	}
	
	@Bean
	public AuthenticationSuccessHandler authenticationSuccessHandler() {
		return new CustomLoginSuccessHandler();
	}
	
	// PersistentTokenRepository 구현 클래스 객체 생성
	private PersistentTokenRepository createJDBCRepository() {
		JdbcTokenRepositoryImpl repo = new JdbcTokenRepositoryImpl();
		repo.setDataSource(datasource);
		return repo;
	}
	
//	@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);
//	}
}

 

datasource가 AuthenticationConfig.java에도 있었지만, 서로 충돌하지 않는 듯 하다.

반응형

댓글()