인증(Authentication)

https://github.com/beginner0107/bank/commit/aaa63af514db6dff6955ebdfc31ad296f8ea9be3?diff=split

SecurityConfig 구성 파일 수정

	// Exception 가로채기
        http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
            CustomResponseUtil.unAuthentication(response, "로그인을 진행해 주세요.");
        });
  • 인증 -> 인증 관련 오류가 발생했을 때
  • CustomResponseUtil이름이 있는 클래스에서는 오류 메시지가 json 형식으로 본문에 표시됩니다.

CustomResponseUtil.class

public class CustomResponseUtil {
    private static final Logger log = LoggerFactory.getLogger(CustomResponseUtil.class);

    public static void unAuthentication(HttpServletResponse response, String msg) {
        try {
            ObjectMapper om = new ObjectMapper();
            ResponseDto<?> responseDto = new ResponseDto<>(-1, msg, null);
            String responseBody = om.writeValueAsString(responseDto);
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(401);
            response.getWriter().println(responseBody);
        } catch (Exception e) {
            log.error("서버 파싱 에러");
        }
    }
}
  • ObjectMapperResponseDto는 json 형식의 문자열로 구문 분석할 수 있습니다.
  • 왜 response.setStatus(401)입니까?
  • https://mangkyu.146

(HTTP) HTTP 상태 401(권한 없음)과 403(금지됨)의 차이점

1. HTTP 상태 401(권한 없음)과 403(금지됨)의 차이점 (HTTP 상태 401(권한 없음)이란 무엇입니까?) HTTP 상태 중 401(권한 없음)은 클라이언트가 인증되지 않았거나 요청이 거부되었음을 의미합니다. 유효한 인증 정보가 부족합니다.

mangkyu.tistory.com

  • 401은 인증 관련, 403은 인증 관련 상태 코드입니다.
  • 여기서 setStatus가 설정되지 않은 경우(PostMan으로 확인) 상태 코드 401이 표시되는 것을 볼 수 있습니다.

ResponseDto.class

@RequiredArgsConstructor
@Getter
public class ResponseDto <T>{
    private final Integer code; // 1. 성공, -1 실패
    private final String msg;
    private final T data;
}