6. 사용자 정의 접근 거부 처리자

책의 6. 사용자 정의 접근 거부 처리자의 내용

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

 

CustomAccessDeniedHandler.java

@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException, ServletException {
		// TODO Auto-generated method stub
		log.info("handle");
		response.sendRedirect("/accessError");

	}

}
반응형

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

8. 로그인 성공 처리  (0) 2023.05.19
7. 사용자 정의 로그인 페이지  (0) 2023.04.30
5. 접근 거부 처리  (0) 2023.04.22
4. 로그인 처리  (0) 2023.04.16
3. 접근 제한 설정  (0) 2023.04.16

댓글()