• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

접근이 거부되었습니다. 예외가 발생합니다.

23.03.21 13:10 작성 조회수 1.92k

0

5) 웹 기반 인가처리 DB 연동 - FilterInvocationSecurityMetadataSource (2) 강의 관련 질문입니다.

 

참고로, 현재 SecurityConfig 파일이 파일명으로 구분해서 Ajax 인증용과 폼인증 두개 입니다.

문제는 로그인까지 성공하고 /mypage 로 들어가면 접근 거부 예외가 생깁니다.

'org.springframework.security.access.AccessDeniedException: 접근이 거부되었습니다.'

 

SecurityConfig , AjaxSecurityConfig 설정파일명으로 구분했고 마지막에

설정 코드도 올렸지만 authenticationManager 같은 Bean 메서드들도 이름으로 구분했습니다.

 

사용자정보, 권한정보등 제대로 갖고 왔는데 어디가 잘못된건지 잘모르겠네요..

혹시 시큐리티 설정파일에서 서비스 클래스 두가지를 사용해서 그런지 의심도 되고 그렇네요..

private final SecurityResourceService securityResourceService;

private final UserDetailsService userDetailsService;

 

아래에 도움이 될까 해서 디버깅화면 캡쳐해서 올렸습니다.

그리고 코드는 아래 깃허브에 올렸습니다.

walnutnamu/corespringsecurity (github.com)

감사합니다.

 

AbstractSecurityInterceptor 클래스

UrlFilterInvocationSecurityMetadataSource 클래스

 

RoleVoter 클래스

ExceptionTranslationFilter 클래스

FormAccessDeniedHandler 클래스

AccessDeniedException 클래스

 


웹페이지에는 흰 배경만 나타나고 302 코드를 반환하네요.

  1. Request URL:http://localhost:8080/mypage

  2. Request Method:GET

  3. Status Code:302

  4. Remote Address:[::1]:8080

  5. Referrer Policy:strict-origin-when-cross-orig

 

 

  


시큐리티 설정파일

 

@Configuration

@RequiredArgsConstructor

@Order(1)

public class SecurityConfig {

@Bean

public WebSecurityCustomizer configure() {

return (web) -> web.ignoring().mvcMatchers(

"/css/**",

"/js/**",

"/error"

);

}

private final AuthenticationConfiguration authenticationConfiguration;

private final AuthenticationDetailsSource authenticationDetailsSource;

private final AuthenticationSuccessHandler formAuthenticationSuccessHandler;

private final AuthenticationFailureHandler formAuthenticationFailureHandler;

private final SecurityResourceService securityResourceService;

private final UserDetailsService userDetailsService;

public PasswordEncoder passwordEncoder() {

return PasswordEncoderFactories.createDelegatingPasswordEncoder();

}

@Bean

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http

.authorizeRequests()

.antMatchers("/", "/users", "user/login/**", "/login*").permitAll()

.antMatchers("/mypage").hasRole("USER")

.antMatchers("/messages").hasRole("MANAGER")

.antMatchers("/config").hasRole("ADMIN")

.anyRequest().authenticated()

.and()

.exceptionHandling()

//.accessDeniedPage("/denied")

.accessDeniedHandler(accessDeniedHandler())

.and()

.addFilterBefore(customFilterSecurityInterceptor(), FilterSecurityInterceptor.class)

;

http

.formLogin()

.loginPage("/login")

.loginProcessingUrl("/login_proc")

.authenticationDetailsSource(authenticationDetailsSource)

.defaultSuccessUrl("/")

.successHandler(formAuthenticationSuccessHandler)

.failureHandler(formAuthenticationFailureHandler)

.permitAll()

;

//http.csrf().disable();

return http.build();

}

public FormAuthenticationProvider formAuthenticationProvider() {

return new FormAuthenticationProvider(userDetailsService, passwordEncoder());

}

@Bean

public AccessDeniedHandler accessDeniedHandler(){

FormAccessDeniedHandler accessDeniedHandler = new FormAccessDeniedHandler();

accessDeniedHandler.setErrorPage("/denied");

return accessDeniedHandler;

}

@Bean

public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {

ProviderManager authenticationManager = (ProviderManager) authenticationConfiguration.getAuthenticationManager();

authenticationManager.getProviders().add(formAuthenticationProvider());

return authenticationManager;

}

@Bean

public FilterSecurityInterceptor customFilterSecurityInterceptor() throws Exception {

FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor();

filterSecurityInterceptor.setSecurityMetadataSource(urlFilterInvocationSecurityMetadataSource());

filterSecurityInterceptor.setAccessDecisionManager(affirmativeBased());

filterSecurityInterceptor.setAuthenticationManager(authenticationManager(authenticationConfiguration));

return filterSecurityInterceptor;

}

public AccessDecisionManager affirmativeBased() {

AffirmativeBased affirmativeBased = new AffirmativeBased(getAccessDecisionVoters());

return affirmativeBased;

}

private List<AccessDecisionVoter<?>> getAccessDecisionVoters() {

return Arrays.asList(new RoleVoter());

}

/**

* 자원/권한 정보를 저장하고 있는 클래스를 빈으로 생성

* @return

* @throws Exception

*/

@Bean

public FilterInvocationSecurityMetadataSource urlFilterInvocationSecurityMetadataSource() throws Exception {

return new UrlFilterInvocationSecurityMetadataSource(urlResourcesMapFactoryBean().getObject());

}

private UrlResourcesMapFactoryBean urlResourcesMapFactoryBean() {

UrlResourcesMapFactoryBean urlResourcesMapFactoryBean = new UrlResourcesMapFactoryBean();

urlResourcesMapFactoryBean.setSecurityResourceService(securityResourceService);

return urlResourcesMapFactoryBean;

}

}

 

답변 1

답변을 작성해보세요.

0

공유해 주신 소스를 실행해 보면 관리자로 접속할 수 있는 메뉴가 안보이고 리소스와 권한을 매핑해서 DB 에서 참조할 수 있도록 해야 하는데 이런 부분들이 소스에서 누락되어 있는 것 같습니다.

image로그인 페이지에서 보면 관리자 메뉴가 안보입니다.

테스트 시 /mypage 리소스에 "ROLE_USER,ROLE_MANAGER,ROLE_USER" 를 매핑을 어떻게 하셨는지요?

 

원데이님의 프로필

원데이

질문자

2023.03.26

AJAX 부분이 추가 되면서 부터 좀 많이 헷갈리네요..

폼인증과 AJAX 인증 방식 섞이면서 꼬인것 같습니다.

버전도 다르고 강의코드도 갑자기 추가된 부분이 있어 구글링 해서 하다 보니 어렵네요 ㅜ

일단 여기서 중지하고 처음부터 다시 보는게 좋을것 같네요.