Skip to content

Commit

Permalink
refactor: 401에러 반환을 위한 EntryPoint 코드 수정 (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
pdohyung committed Nov 16, 2023
1 parent 22c545f commit 13a0a3a
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 6 deletions.
12 changes: 10 additions & 2 deletions src/main/java/com/backend/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.backend.jwt.filter.JwtAuthenticationFilter;
import com.backend.jwt.service.JwtProvider;
import com.backend.jwt.service.ApiUserDetailsService;
import com.backend.util.LoginUserArgumentResolver;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -18,10 +19,13 @@
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;

import java.util.List;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
Expand Down Expand Up @@ -59,8 +63,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.requestMatchers(mvcMatcherBuilder.pattern("/mail/**")).permitAll()
.anyRequest().authenticated())
.exceptionHandling()
.authenticationEntryPoint(entryPoint)
.accessDeniedHandler(deniedHandler);
.authenticationEntryPoint(entryPoint);
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

return http.getOrBuild();
Expand All @@ -84,4 +87,9 @@ public void addCorsMappings(CorsRegistry registry) {
.allowedHeaders("*")
.exposedHeaders("*");
}

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new LoginUserArgumentResolver());
}
}
4 changes: 2 additions & 2 deletions src/main/java/com/backend/error/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ public enum ErrorCode {
ALREADY_LOGOUT_MEMBER(BAD_REQUEST, "이미 로그아웃한 회원입니다."),
ALREADY_EXIST_EMAIL(BAD_REQUEST, "이미 존재하는 이메일입니다."),
INVALID_TOKEN(UNAUTHORIZED, "잘못된 토큰입니다."),
INVALID_GROUP_TYPE(UNAUTHORIZED, "잘못된 그룹 종류입니다."),
INVALID_PASSWORD(UNAUTHORIZED, "잘못된 비밀번호입니다.");
INVALID_GROUP_TYPE(BAD_REQUEST, "잘못된 그룹 종류입니다."),
INVALID_PASSWORD(BAD_REQUEST, "잘못된 비밀번호입니다.");

private final int code;
private final String message;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,48 @@
package com.backend.jwt.filter;

import com.backend.error.dto.ErrorResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@RequiredArgsConstructor
public class ApiAuthenticationEntryPoint implements AuthenticationEntryPoint {

private final ObjectMapper objectMapper;

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {

log.info("엔트리 포인트");

String json = objectMapper.writeValueAsString(ErrorResponse.of(HttpStatus.UNAUTHORIZED.value(),
"인증되지 않은 사용자 입니다."));

setResponseProperties(response);
writeJsonToResponse(response, json);
}

private void setResponseProperties(HttpServletResponse response) {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}

private void writeJsonToResponse(HttpServletResponse response, String json) throws IOException {
response.getWriter().write(json);
}
}

0 comments on commit 13a0a3a

Please sign in to comment.