inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발

API 사용을 위한 사용자 인증 처리 구현

인증 실패 시 HTTP Satuts code 200

637

도롱

작성한 질문수 1

0

안녕하세요. 강의 보면서 따라하다가 궁금한 점 하나가 생겨서 질문드립니다.

아이디 혹은 비밀번호를 일부러 틀리게 입력 시 stuatus code가 200이 출력되는데 강의에서는 401로 출력되더라고요. 제가 생각해도 200 ok는 아닌 거 같은데.. 따로 설정해줘야 하나요?

SecurityConfig.java

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'

 

확인 부탁드립니다.. 감사합니다.

 

 

spring-boot rest-api

답변 1

0

휴지보다비데

저도 그랬는데 postman 껏다 키니까 되긴 하네요...

JPA

0

63

1

jpa dependency를 추가하고 SecurityConfig클래스에서 오류가 납니다.

0

72

1

웹 브라우저 400 bad request

0

73

1

@Size는 되는데 @Past는 안 됩니다.

0

65

1

pdf 자료는 없나요?

0

78

2

locale 정보가 null 이면 무조건 messages_ko.properties이 호출 되는 문제

0

91

2

Swagger 강의, Unable to infer base url 이거 뜨시는 분들 도움되시라고

0

122

1

강의에서나온 화면 피피티

0

161

1

HelloWorldBean 관련 에러

0

189

2

Swagger API 3.x 오류..

0

223

1

java: variable message not initialized in the default constructor 에러는 어찌하면 좋을까요?

1

283

1

현재 GIT에 올리신 소스를 실행해봤습니다.

0

191

2

고양이 소리가 귀엽네요 !!

0

140

2

git에서 소스받고 실습중인데

0

120

1

post가 안되요

0

107

1

한국어 같은 경우 언어코드인 messages_ko.properties 로 생성하는게 더 좋지 않나요?

0

169

2

리턴타입으로서 EntityModel<User> 와 ResponseEntity질문

0

107

1

예외처리쪽 관련 질문있습니다.

0

161

2

엔티티가 바로 응답으로 나가도 되나요??

0

230

2

안녕하세여 Cannot invoke "co.kr.joneconsulting.resfulservice.repository.PostRepository.save(Object)" because "this.postRepository" is null

0

143

2

사용자 등록하고 나서 H2 에서 보면 신규 사용자의 password, ssn 이 null 로 되어 있습니다.

0

144

2

ApplictionContext 질문

0

197

2

롬북이 안먹히는것같아요

0

159

1

인텔리제이에서스프링부트 파일 실행하면

0

242

1