작성
·
571
0
안녕하세요. 강의 보면서 따라하다가 궁금한 점 하나가 생겨서 질문드립니다.
아이디 혹은 비밀번호를 일부러 틀리게 입력 시 stuatus code가 200이 출력되는데 강의에서는 401로 출력되더라고요. 제가 생각해도 200 ok는 아닌 거 같은데.. 따로 설정해줘야 하나요?
package com.example.restfulwebservice.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
@Configuration
public class SecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("test")
.password("{noop}test1234")
.roles("USER");
}
}
CustomizedResponseEntityExceptionHandler.java
@RestController
@ControllerAdvice // 모든 컨트롤러가 실행될 때 이 어노테이션이 붙은 Bean이 사전에 실행되도록 한다.
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class) // 이 메서드가 ExceptionHandler 라는 걸 알려주는 어노테이션
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse
= new ExceptionResponse(LocalDateTime.now(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
// user 클래스 전용
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse
= new ExceptionResponse(LocalDateTime.now(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
List<FieldError> list = ex.getBindingResult().getFieldErrors();
ExceptionResponse exceptionResponse = new ExceptionResponse(LocalDateTime.now(),
"Validation Failed : " + list.get(0).getField(), ex.getBindingResult().toString());
return new ResponseEntity(exceptionResponse,HttpStatus.BAD_REQUEST);
}
}
application.yml
server:
port: 8088
logging:
level:
org.springframework : DEBUG
spring:
messages:
basename: messages
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
security:
user:
name: username
password: test1
management:
endpoints:
web:
exposure:
include: "*"
build.gradle
// security
implementation 'org.springframework.boot:spring-boot-starter-security'
확인 부탁드립니다.. 감사합니다.