Programming-[Backend]/SpringBoot
[TIL][Spring security] hasRole 적용 시 access is denied 문제
컴퓨터 탐험가 찰리
2022. 1. 20. 21:22
728x90
반응형
문제
SecurityConfig에서 hasRole("MANAGER")로 권한을 주었는데도 "/messages" 페이지에 대한 접근이 불가했다.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// .antMatchers("/mypage").hasRole("USER")
.antMatchers("/messages").hasRole("MANAGER")
// .antMatchers("/config").hasRole("ADMIN")
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login_proc")
.defaultSuccessUrl("/")
.authenticationDetailsSource(authenticationDetailsSource)
.successHandler(customAuthenticationSuccessHandler)
.failureHandler(customAuthenticationFailureHandler)
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler())
;
}
해결
Spring Security에서 Role의 경우에는 prefix로 "ROLE_" 이라는 문자를 붙인다. 따라서 다음의 둘 중 하나를 선택해서 적용해야 한다.
- DB상 role 정보에 prefix로 "ROLE_"을 붙여준다.
- hasRole 대신 hasAuthority를 사용한다.
or
.antMatchers("/messages").hasAuthority("MANAGER")
따져보면 Role이나 Authority나 모두 "권한" 정보이다. 그리고 hasRole 안에 "ROLE_" prefix를 직접 넣어주면 spring security가 넣어줘서 판단하니 직접 넣지 말라는 컴파일 에러도 발생한다.
Caused by: java.lang.IllegalArgumentException: role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_MANAGER'
참조
1. StackOverFlow
728x90
반응형