7. 사용자 정의 로그인 페이지

책의 7. 사용자 정의 로그인 페이지의 설명

SecurityConfig.java

@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();
		
		//접근 거부 처리자의 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 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);
	}
}

LoginController.java

LoginFrom.html

책 내용 참고

반응형

'스프링 시큐리티 > 책 내용 정리' 카테고리의 다른 글

9. 로그아웃 처리  (0) 2023.05.20
8. 로그인 성공 처리  (0) 2023.05.19
6. 사용자 정의 접근 거부 처리자  (0) 2023.04.30
5. 접근 거부 처리  (0) 2023.04.22
4. 로그인 처리  (0) 2023.04.16

댓글()