작성
·
24
0
의도적으로 토큰을 누락하면 403 포비든이 발생하는데, 이는 말씀하신데로 filterConfig에서 에러를 잡는다고 하면,
해당 에러 코드와 내용을 커스텀 하려면 어떻게 처리하나요?
일단 컨트롤러까지 제어가 안오고 바로 에러가 반환되는듯하네요
답변 2
0
안녕하세요~ 말씀해주신바와같이, 토큰을 누락하고 요청을 보낸경우 filterchain레벨에서 에러가 터져서 컨트롤러까지 이어지지 못합니다.
그래서 아래 AI에서 답변한것과 같이,
securityconfig에서 에러 핸들러를 추가 해야 합니다.
filterchain에서 발생하는 에러를 catch하여 커스텀할수있도록 코드추가가 필요합니다.
AccessDeniedHandler는 컨트롤러 까지 제어가 넘어 왔을 때 작동하는것 같은데요,,,
예를 들어 특정 엔드포인트 ROLE권한(@PreAuthorize) 체크시 발생,,
현재 코드는 토큰 미발행 조건은 따로 체크하지 않고, 무조건 엔드 포인트까지 흘러가는데 403포비든 에러가 filterchain에서 바로 반환되는듯하네요,
물론 토큰 검증을 한 후 넘어가면 되겠지만, 이 경우에는 filterchain이 던지는 403 에러는 커스텀이 불가능한가요?
안녕하세요~! filterchain에서 403에 대한 커스텀은 보통 아래와 같이 합니다. 아래 코드 한번 참고 해보실수 있을까요?
SecurityConfig코드
private final JwtTokenFilter jwtTokenFilter;
private final JwtAuthenticationHandler jwtAuthenticationHandler;
private final JwtAuthorizationHandler jwtAuthorizationHandler;
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.cors(c->c.configurationSource(corsConfiguration()))
.csrf(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.sessionManagement(s->s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling(e->
e.authenticationEntryPoint(jwtAuthenticationHandler) //401의 경우
.accessDeniedHandler(jwtAuthorizationHandler) //403의 경우
)
403관련 핸들러 코드
//403에러인경우
@Component
@Slf4j
public class JwtAuthorizationHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
log.error(accessDeniedException.getMessage());
response.setStatus(HttpServletResponse.SC_FORBIDDEN);//403
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
CommonErrorDto dto = new CommonErrorDto(403, "권한이 없습니다.");
ObjectMapper objectMapper = new ObjectMapper();
String body = objectMapper.writeValueAsString(dto);
PrintWriter printWriter = response.getWriter();
printWriter.write(body);
printWriter.flush();
}
}
0
안녕하세요, 인프런 AI 인턴입니다. 트릴님.
질문 내용에 따르면, 토큰이 필요한 엔드포인트에서 토큰 누락 시 발생하는 403 Forbidden 에러를 커스텀하고 싶으신 것 같습니다. 기본적으로 Spring Security는 인증이 필요한 엔드포인트에 토큰이 없을 경우 403 에러를 반환합니다. 이를 커스텀하기 위해서는 다음과 같은 방법을 고려할 수 있습니다:
AccessDeniedHandler
를 구현하여 커스텀 메시지를 반환할 수 있습니다. 이를 통해 사용자에게 좀 더 명확한 에러 정보를 제공할 수 있습니다. import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
org.springframework.security.access.AccessDeniedException accessDeniedException) throws IOException {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Custom Access Denied Message");
}
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// other configurations
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler());
}
}
doFilter
메서드를 오버라이드하여 요청을 가로채고, 토큰이 없거나 유효하지 않은 경우에 커스텀 에러를 반환할 수 있습니다.위의 방법을 참고하여 에러 메시지를 커스텀하고, 보다 명확한 정보를 사용자에게 제공할 수 있습니다. 관련된 더 많은 정보를 얻고자 하신다면 아래의 링크를 참고하세요:
저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.
감사합니다.