프레임워크/Spring

[Spring] Rest API 서버 만들기 1 - 문서화, 구조, Exception, Security

pythaac 2022. 6. 5. 16:16

https://daddyprogrammer.org/post/series/springboot2-make-rest-api/

 

SpringBoot2로 Rest api 만들기 - 강좌모음

SpringBoot2로 Rest api 만들기 - 강좌모음

daddyprogrammer.org

 

  • 1. Intellij Community 프로젝트 생성
  • 2. HelloWorld
  • 3. H2 Database 연동
  • 4. Swagger API 문서 자동화
  • 5. API 인터페이스 및 결과 데이터 구조 설계
  • 6. ControllerAdvice를 이용한 Exception 처리
  • 7. MessageSource를 이용한 Exception 처리
  • 8. SpringSecurity를 이용한 인증 및 권한 부여

 

1. Intellij Community 프로젝트 생성

  • 프로젝트 설정
    • Gradle
    • Java 11
    • Spring Boot 2.7.0
    • Jar
  • Dependency
    • Spring Web
    • Spring Security
    • Spring Data JPA
    • Spring Data Redis
    • Lombok
    • Mysql Driver
    • H2 Database

 

2. Hello World

  • package
    • [정의] class를 구분하기 위한 방법
    • [특징] 계층 구조
  • @SpringBootApplication
    • [정의] 자동 설정을 위한 어노테이션
    • [기능] 3가지 어노테이션 포함
      • @EnableAutoConfiguration
        • META-INF/spring.factories에 정의된 configuration 대상 클래스들을 빈으로 등록
      • @SpringBootConfiguration
        • context에 있는 추가적인 빈 등록
      • @ComponentScan
        • package에 포함된 @Component를 scan

https://velog.io/@jwkim/spring-boot-springapplication-annotation

 

[Spring Boot] @SpringBootApplication 파헤치기

[Spring Boot] @SpringBootApplication 얜 뭐지

velog.io

  • application.properties
    • [정의] 프로젝트 환경설정 값 저장
      - ex) 포트 번호
      - server.port=8080
  • Controller
    • 클라이언트 요청의 진입점이 되는 Class

 

3. H2 Database 연동

  • Lombok
    • @Builder
      - 빌더 클래스 생성

 

4. Swagger API 문서 자동화

  • 특징
    • Postman없이 테스트 가능한 Web UI 지원
    • 자동 API Document 생성
  • dependency
implementation 'io.springfox:springfox-swagger2:2.6.1'
implementation 'io.springfox:springfox-swagger-ui:2.6.1'
  • SwaggerConfiguration
    • basePackage("com.rest.api.controller")).paths(PathSelectors.any())
      - "com.rest.api.controller" 아래 Controller 내용을 읽어 mapping된 resource들을 문서화
    • PathSelectors.any("/v1/**")
      - v1으로 시작하는 resource들만 문서화
    • swaggerInfo
      - 문서 설명, 작성자 정보 등을 노출
// https://daddyprogrammer.org/post/313/swagger-api-doc/

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    @Bean
    public Docket swaggerApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(swaggerInfo()).select()
                .apis(RequestHandlerSelectors.basePackage("com.rest.api.controller"))
                .paths(PathSelectors.any())
                .build()
                .useDefaultResponseMessages(false); // 기본으로 세팅되는 200,401,403,404 메시지를 표시 하지 않음
    }

    private ApiInfo swaggerInfo() {
        return new ApiInfoBuilder().title("Spring API Documentation")
                .description("앱 개발시 사용되는 서버 API에 대한 연동 문서입니다")
                .license("happydaddy").licenseUrl("http://daddyprogrammer.org").version("1").build();
    }
}
  • [의견] 그런데 실제 코드에 애노테이션을 붙여야해서 지저분하다
    • @Api
    • @ApiOperation
    • @ApiParam
  • Spring Rest Docs
    • API 문서화하는 다른 방법
    • 테스트는 안되지만 코드에 애노테이션을 붙일 필요가 없다고 함

https://techblog.woowahan.com/2597/

 

Spring Rest Docs 적용 | 우아한형제들 기술블로그

{{item.name}} 안녕하세요? 우아한형제들에서 정산시스템을 개발하고 있는 이호진입니다. 지금부터 정산시스템 API 문서를 wiki 에서 Spring Rest Docs 로 전환한 이야기를 해보려고 합니다. 1. 전환하는

techblog.woowahan.com


 

5. API 인터페이스 및 결과 데이터 구조 설계

  • HTTP method를 사용하고, Restful API를 위한 규칙

 

1. 리소스 사용 목적에 따라 HTTP method 구분 사용

  • GET
    - 읽기 : 서버에 리소스의 정보 요청
  • POST
    - 쓰기 : 서버에 리소스를 제출하여 생성
  • PUT
    - 수정 : 서버에 리소스를 제출하여 갱신
  • DELETE
    - 삭제 : 서버에 리소스의 삭제 요청

 

2. Mapping 주소 체계 정형화

  • 정형화된 구조로 구성 후 HTTP method로 목적 판단
GET /v1/user/{userId} - ID로 회원 정보 조회
GET /v1/users - 회원 리스트 조회
POST /v1/user - 신규 회원정보 입력
PUT /v1/user - 기존 회원정보 수정
DELETE /v1/user/{userId} - ID로 회원 정보 삭제

 

3. 결과 데이터 구조 표준화

  • 구성
    - 결과 데이터 + API 요청 결과
// https://daddyprogrammer.org/post/404/spring-boot2-design-api-interface-and-data-structure/

// 기존 USER 정보
{
    "msrl": 1,
    "uid": "yumi@naver.com",
    "name": "정유미"
}
// 표준화한 USER 정보
{
  "data": {
    "msrl": 1,
    "uid": "yumi@naver.com",
    "name": "정유미"
  },
  "success": true
  "code": 0,
  "message": "성공하였습니다."
}

 

  • 결과 모델 정의
    • api 실행 결과를 담는 공통 모델
      • success
      • code
      • msg
    • 결과가 단일건인 api를 담는 모델
    • 결과가 여러건인 api를 담는 모델
// https://daddyprogrammer.org/post/404/spring-boot2-design-api-interface-and-data-structure/

@Getter
@Setter
public class CommonResult {

    @ApiModelProperty(value = "응답 성공여부 : true/false")
    private boolean success;

    @ApiModelProperty(value = "응답 코드 번호 : >= 0 정상, < 0 비정상")
    private int code;

    @ApiModelProperty(value = "응답 메시지")
    private String msg;
}

@Getter
@Setter
public class SingleResult<T> extends CommonResult {
    private T data;
}

@Getter
@Setter
public class ListResult<T> extends CommonResult {
    private List<T> list;
}
  • 결과 모델을 처리할 service 정의
    • API 요청 결과를 enum으로 정의
    • 단일 결과 처리 메서드
    • 다중건 결과 처리 메서드
    • 성공 결과만 처리하는 메서드
    • 실패 결과만 처리하는 메서드
    • 결과 모델에 API 요청 성공 데이터를 세팅해주는 메서드
// https://daddyprogrammer.org/post/404/spring-boot2-design-api-interface-and-data-structure/

@Service // 해당 Class가 Service임을 명시합니다.
public class ResponseService {

    // enum으로 api 요청 결과에 대한 code, message를 정의합니다.
    public enum CommonResponse {
        SUCCESS(0, "성공하였습니디."),
        FAIL(-1, "실패하였습니다.");

        int code;
        String msg;

        CommonResponse(int code, String msg) {
            this.code = code;
            this.msg = msg;
        }

        public int getCode() {
            return code;
        }

        public String getMsg() {
            return msg;
        }
    }
    // 단일건 결과를 처리하는 메소드
    public <T> SingleResult<T> getSingleResult(T data) {
        SingleResult<T> result = new SingleResult<>();
        result.setData(data);
        setSuccessResult(result);
        return result;
    }
    // 다중건 결과를 처리하는 메소드
    public <T> ListResult<T> getListResult(List<T> list) {
        ListResult<T> result = new ListResult<>();
        result.setList(list);
        setSuccessResult(result);
        return result;
    }
    // 성공 결과만 처리하는 메소드
    public CommonResult getSuccessResult() {
        CommonResult result = new CommonResult();
        setSuccessResult(result);
        return result;
    }
    // 실패 결과만 처리하는 메소드
    public CommonResult getFailResult() {
        CommonResult result = new CommonResult();
        result.setSuccess(false);
        result.setCode(CommonResponse.FAIL.getCode());
        result.setMsg(CommonResponse.FAIL.getMsg());
        return result;
    }
    // 결과 모델에 api 요청 성공 데이터를 세팅해주는 메소드
    private void setSuccessResult(CommonResult result) {
        result.setSuccess(true);
        result.setCode(CommonResponse.SUCCESS.getCode());
        result.setMsg(CommonResponse.SUCCESS.getMsg());
    }
}
  • HTTP Method와 정형화된 주소체계로 Controller 작성
// https://daddyprogrammer.org/post/404/spring-boot2-design-api-interface-and-data-structure/

@Api(tags = {"1. User"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/v1")
public class UserController {

    private final UserJpaRepo userJpaRepo;
    private final ResponseService responseService; // 결과를 처리할 Service

    @ApiOperation(value = "회원 리스트 조회", notes = "모든 회원을 조회한다")
    @GetMapping(value = "/users")
    public ListResult<User> findAllUser() {
        // 결과데이터가 여러건인경우 getListResult를 이용해서 결과를 출력한다.
        return responseService.getListResult(userJpaRepo.findAll());
    }

    @ApiOperation(value = "회원 단건 조회", notes = "userId로 회원을 조회한다")
    @GetMapping(value = "/user/{msrl}")
    public SingleResult<User> findUserById(@ApiParam(value = "회원ID", required = true) @PathVariable long msrl) {
        // 결과데이터가 단일건인경우 getBasicResult를 이용해서 결과를 출력한다.
        return responseService.getSingleResult(userJpaRepo.findById(msrl).orElse(null));
    }

    @ApiOperation(value = "회원 입력", notes = "회원을 입력한다")
    @PostMapping(value = "/user")
    public SingleResult<User> save(@ApiParam(value = "회원아이디", required = true) @RequestParam String uid,
                                   @ApiParam(value = "회원이름", required = true) @RequestParam String name) {
        User user = User.builder()
                .uid(uid)
                .name(name)
                .build();
        return responseService.getSingleResult(userJpaRepo.save(user));
    }

    @ApiOperation(value = "회원 수정", notes = "회원정보를 수정한다")
    @PutMapping(value = "/user")
    public SingleResult<User> modify(
            @ApiParam(value = "회원번호", required = true) @RequestParam long msrl,
            @ApiParam(value = "회원아이디", required = true) @RequestParam String uid,
            @ApiParam(value = "회원이름", required = true) @RequestParam String name) {
        User user = User.builder()
                .msrl(msrl)
                .uid(uid)
                .name(name)
                .build();
        return responseService.getSingleResult(userJpaRepo.save(user));
    }

    @ApiOperation(value = "회원 삭제", notes = "userId로 회원정보를 삭제한다")
    @DeleteMapping(value = "/user/{msrl}")
    public CommonResult delete(
            @ApiParam(value = "회원번호", required = true) @PathVariable long msrl) {
        userJpaRepo.deleteById(msrl);
        // 성공 결과 정보만 필요한경우 getSuccessResult()를 이용하여 결과를 출력한다.
        return responseService.getSuccessResult();
    }
}

 

6. ControllerAdvice를 이용한 Exception 처리

  • 용도
    • 특정한 Exception이 발생할 경우 공통으로 처리하는 방법
    • Controller에서 발생하는 Exception을 한군데서 처리 가능
  • 예제 코드
    • @ControllerAdvice / @RestControllerAdvice
      - 차이 : @Controller / @RestController와 같음
    • 특정 패키지 설정
      - @RestControllerAdvice(basePackages = "com.rest.api")
    • @ExceptionHandler(Exception.class)
      - Exception 발생시 해당 Handler로 처리하겠다를 명시
      - Exception.class는 최상위 클래스로, 다른 handler에서 처리되지 않은 모든 예외를 처리
    • @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
      - 해당 Exception 발생시 Response에 출력되는 code 설정
    • responseService.getFailResult()
      - 미리 설정한 실패 결과 json 반환
// https://daddyprogrammer.org/post/446/spring-boot2-5-exception-handling-controlleradvice/

@RequiredArgsConstructor
@RestControllerAdvice
public class ExceptionAdvice {

    private final ResponseService responseService;

    @ExceptionHandler(Exception.class) 
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    protected CommonResult defaultException(HttpServletRequest request, Exception e) {
        return responseService.getFailResult();
    }
}
  • Custom Exception
    • RuntimeException 상속 
    • 생성자 작성
public class CUserNotFoundException extends RuntimeException {
    public CUserNotFoundException(String msg, Throwable t) {
        super(msg, t);
    }
    
    public CUserNotFoundException(String msg) {
        super(msg);
    }
    
    public CUserNotFoundException() {
        super();
    }
}

 

7. MessageSource를 이용한 Exception 처리

  • 다국어 처리
    • i18n 지원 (internationalization)
    • "안녕하세요"를 "Hello"로 표시되도록 할 수 있음
  • message.properties
    • dependency
      >> implementation 'net.rakugakibox.util:yaml-resource-bundle:1.1'
    • 메시지를 yml 형식으로 저장 가능
  • MessageConfiguration
    • AbstractLocaleContextResolver
    • AbstractLocaleResolver
    • AcceptHeaderLocaleResolver
    • CookieLocaleResolver
    • FixedLocaleResolver
    • SessionLocaleResolver
// https://daddyprogrammer.org/post/499/springboot2-exception-handling-with-messagesource/

@Configuration
public class MessageConfiguration implements WebMvcConfigurer {

    @Bean // 세션에 지역설정. default는 KOREAN = 'ko'
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.KOREAN);
        return slr;
    }

    @Bean // 지역설정을 변경하는 인터셉터. 요청시 파라미터에 lang 정보를 지정하면 언어가 변경됨.
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override // 인터셉터를 시스템 레지스트리에 등록
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

    @Bean // yml 파일을 참조하는 MessageSource 선언
    public MessageSource messageSource(
            @Value("${spring.messages.basename}") String basename,
            @Value("${spring.messages.encoding}") String encoding
    ) {
        YamlMessageSource ms = new YamlMessageSource();
        ms.setBasename(basename);
        ms.setDefaultEncoding(encoding);
        ms.setAlwaysUseMessageFormat(true);
        ms.setUseCodeAsDefaultMessage(true);
        ms.setFallbackToSystemLocale(true);
        return ms;
    }

    // locale 정보에 따라 다른 yml 파일을 읽도록 처리
    private static class YamlMessageSource extends ResourceBundleMessageSource {
        @Override
        protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException {
            return ResourceBundle.getBundle(basename, locale, YamlResourceBundle.Control.INSTANCE);
        }
    }
}
  • application.preperties에 i8n 경로 및 인코딩 정보 추가
    • spring:
        messages:
          basename: i18n/exception
          encoding: UTF-8
  • 다국어 처리 message yml 생성
    • resources 아래에 i18n 디렉토리 생성
    • exception_en.yml, exception_ko.yml 생성
# exception_en.yml
unKnown:
  code: "-9999"
  msg: "An unknown error has occurred."
userNotFound:
  code: "-1000"
  msg: "This member not exist"
# exception_ko.yml
unKnown:
  code: "-9999"
  msg: "알수 없는 오류가 발생하였습니다."
userNotFound:
  code: "-1000"
  msg: "존재하지 않는 회원입니다."
  • ResponseService의 getFailResult() 메소드에 code, msg를 받도록 수정
public CommonResult getFailResult(int code, String msg) {
    CommonResult result = new CommonResult();
    result.setSuccess(false);
    result.setCode(code);
    result.setMsg(msg);
    return result;
}
  • ExceptionAdvice의 에러 메시지를 messageSource 내용으로 교체
@RequiredArgsConstructor
@RestControllerAdvice
public class ExceptionAdvice {

    private final ResponseService responseService;

    private final MessageSource messageSource;

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    protected CommonResult defaultException(HttpServletRequest request, Exception e) {
        // 예외 처리의 메시지를 MessageSource에서 가져오도록 수정
        return responseService.getFailResult(Integer.valueOf(getMessage("unKnown.code")), getMessage("unKnown.msg"));
    }

    @ExceptionHandler(CUserNotFoundException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    protected CommonResult userNotFoundException(HttpServletRequest request, CUserNotFoundException e) {
        // 예외 처리의 메시지를 MessageSource에서 가져오도록 수정
        return responseService.getFailResult(Integer.valueOf(getMessage("userNotFound.code")), getMessage("userNotFound.msg"));
    }

    // code정보에 해당하는 메시지를 조회합니다.
    private String getMessage(String code) {
        return getMessage(code, null);
    }
    // code정보, 추가 argument로 현재 locale에 맞는 메시지를 조회합니다.
    private String getMessage(String code, Object[] args) {
        return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
    }
}

 

8. SpringSecurity를 이용한 인증/권한부여

  • api 서버의 사용 권한 제한
  • SpringSecurity
    • Spring boot 기반 프로젝트에서 쉽게 보안 처리 구현
    • Spring DispatcherServlet 앞단에 Filter를 등록하여 요청을 가로챔
    • 권한이 없으면 인증 화면으로 리다이렉팅

https://daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/

  • SpringSecurity Filter
    •  특징
      • SpringSecurity는 기능별 필터의 집합
      • 필터에는 처리 순서가 존재
    • 종류
      • ChannelProcessingFilter, SecurityContextPersistenceFilter, ConcurrentSessionFilter, HeaderWriterFilter, CsrfFilter, LogoutFilter, X509AuthenticationFilter, AbstractPreAuthenticatedProcessingFilter, CasAuthenticationFilter, UsernamePasswordAuthenticationFilter, ...
    • UsernamePasswordAuthenticationFilter
      • [정의] 접근 권한이 없는 경우 로그인 폼으로 리다이렉팅하는 필터
      • [문제] API 서버는 로그인 폼이 없으므로 권한 없음을 JSON으로 내려줘야함
      • [방법] UsernamePasswordAuthenticationFilter 전에 관련 처리가 필요
  • API 인증/권한부여, 제한된 리소스 요청
    • 인증을 위해 가입/로그인 api 구현
    • 가입시 제한된 리소스에 접근할 수 있는 ROLE_USER 권한 부여
    • SpringSecurity 설정에서 접근 제한이 필요한 리소스에 대해 ROLE_USER 권한을 가져야 접근 가능하도록 설정
    • 권한을 가진 회원이 로그인 성공시 리소스 접근이 가능한 JWT 보안 토큰을 발급
    • JWT 보안 토큰은 권한이 필요한 API 리소스 요청에 사용
  • JWT(JSON Web Token)
    • 용도
      • 로그인이 완료된 클라이언트에게 회원을 구분할 수 있는 값을 넣은 JWT 토큰을 생성하여 발급
      • 클라이언트에서는 권한이 필요한 리소스를 요청할 때 사용
      • 서버에서는 JWT 토큰이 유효한지 확인하고, 회원 정보를 확인하여, 제한된 리소스 제공
    •  특징
      • JSON 객체를 암호화하여 만든 String값
      • 데이터를 포함하는 토큰
  • Dependency
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.jsonwebtoken:jjwt:0.9.1'
  • JwtTokenProvider 생성
    • 역할
      - JWT 토큰 생성 및 유효성 검증
    • 토큰 생성
      - 알고리즘(SignatureAlgorithm.XXXXX)과 비밀키(secretKey)로 토큰 생성
    • 데이터
      - claim 정보에는 토큰에 부가적인 정보 설정 가능
      - ex) 회원 정보
    • 만료
      - setExpiration()으로 expire 시간 설정
    • 유효성 검증
      - resolveToken()
      - HTTP request header에서 토큰값을 가져와 유효성 검사
// https://daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/

package com.rest.api.config.security;

// import 생략

@RequiredArgsConstructor
@Component
public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈

    @Value("spring.jwt.secret")
    private String secretKey;

    private long tokenValidMilisecond = 1000L * 60 * 60; // 1시간만 토큰 유효

    private final UserDetailsService userDetailsService;

    @PostConstruct
    protected void init() {
        secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
    }

    // Jwt 토큰 생성
    public String createToken(String userPk, List<String> roles) {
        Claims claims = Jwts.claims().setSubject(userPk);
        claims.put("roles", roles);
        Date now = new Date();
        return Jwts.builder()
                .setClaims(claims) // 데이터
                .setIssuedAt(now) // 토큰 발행일자
                .setExpiration(new Date(now.getTime() + tokenValidMilisecond)) // set Expire Time
                .signWith(SignatureAlgorithm.HS256, secretKey) // 암호화 알고리즘, secret값 세팅
                .compact();
    }

    // Jwt 토큰으로 인증 정보를 조회
    public Authentication getAuthentication(String token) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUserPk(token));
        return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
    }

    // Jwt 토큰에서 회원 구별 정보 추출
    public String getUserPk(String token) {
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
    }

    // Request의 Header에서 token 파싱 : "X-AUTH-TOKEN: jwt토큰"
    public String resolveToken(HttpServletRequest req) {
        return req.getHeader("X-AUTH-TOKEN");
    }

    // Jwt 토큰의 유효성 + 만료일자 확인
    public boolean validateToken(String jwtToken) {
        try {
            Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken);
            return !claims.getBody().getExpiration().before(new Date());
        } catch (Exception e) {
            return false;
        }
    }
}
  • JwtAuthenticationFilter 생성
    • [역할] JWT가 유효한 토큰인지 인증을 위한 Filter
    • Security 설정시 UsernamePasswordAuthenticationFilter 앞에 설정
// https://daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/

package com.rest.api.config.security;

// import 생략

public class JwtAuthenticationFilter extends GenericFilterBean {

    private JwtTokenProvider jwtTokenProvider;

    // Jwt Provier 주입
    public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) {
        this.jwtTokenProvider = jwtTokenProvider;
    }

    // Request로 들어오는 Jwt Token의 유효성을 검증(jwtTokenProvider.validateToken)하는 filter를 filterChain에 등록합니다.
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String token = jwtTokenProvider.resolveToken((HttpServletRequest) request);
        if (token != null && jwtTokenProvider.validateToken(token)) {
            Authentication auth = jwtTokenProvider.getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        filterChain.doFilter(request, response);
    }
}
  • SpringSecurity Configuration
    • [정의] 서버에 보안 설정 적용
    • 권한 설정
      • permitAll()
        - 아무나 접근 가능한 리소스
      • ROLE_USER
        - 권한이 필요함을 명시
    • filter 설정
      - addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class);
    • 예외 적용
      - Swagger 페이지에 대해 예외 적용
      - configure()
    • 리소스 접근 제한 표현식
      • hasIpAddress(ip) - 접근자의 IP 주소 매칭 확인
      • hasRole(role) - 역할이 부여된 권한(Granted Authority)과 일치 확인
      • hasAnyRole(role) - 부여된 역할 중 일치하는 항목 확인
      • permitAll - 모든 접근자를 항상 승인
      • denyAll - 모든 사용자 접근 거부
      • anonymous - 익명 사용자인지 확인
      • authenticated - 인증된 사용자 확인
      • rememberMe - 사용자가 remember me를 사용하여 인증했는지 확인
      • fullyAuthenticated - 사용자가 모든 크리덴셜을 갖춘 상태에서 인증했는지 확인
//https://daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/

package com.rest.api.config.security;

// import 생략

@RequiredArgsConstructor
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final JwtTokenProvider jwtTokenProvider;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic().disable() // rest api 이므로 기본설정 사용안함. 기본설정은 비인증시 로그인폼 화면으로 리다이렉트 된다.
            .csrf().disable() // rest api이므로 csrf 보안이 필요없으므로 disable처리.
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증하므로 세션은 필요없으므로 생성안함.
            .and()
                .authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
                    .antMatchers("/*/signin", "/*/signup").permitAll() // 가입 및 인증 주소는 누구나 접근가능
                    .antMatchers(HttpMethod.GET, "helloworld/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
                    .anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
            .and()
                .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣는다

    }

    @Override // ignore check swagger resource
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/v2/api-docs", "/swagger-resources/**",
                "/swagger-ui.html", "/webjars/**", "/swagger/**");

    }
}
  • 토큰의 회원정보 처리를 위한 UserDetailService 재정의
@RequiredArgsConstructor
@Service
public class CustomUserDetailService implements UserDetailsService {

    private final UserJpaRepo userJpaRepo;

    public UserDetails loadUserByUsername(String userPk) {
        return userJpaRepo.findById(Long.valueOf(userPk)).orElseThrow(CUserNotFoundException::new);
    }
}
  • User Entity 수정
    • SpringSecurity 보안 적용을 위해 User entity에 UserDetails Class를 상속받아 재정의
    • roles
      - 회원이 가지고 있는 권한 정보
      - 가입시 default "ROLE_USER"
      - 여러 권한을 설정할 수 있도록 Collection으로 선언
    • @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
      - isAccountNonExpired : 계정 만료 확인
      - isAccountNonLocked : 잠긴 계정 확인
      - isCreadnetialsNonExpired : 패스워드 만료 확인
      - isEnabled : 계정 사용 가능 확인
// https://daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/ 

@Builder // builder를 사용할수 있게 합니다.
@Entity // jpa entity임을 알립니다.
@Getter // user 필드값의 getter를 자동으로 생성합니다.
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
public class User implements UserDetails {
    @Id // pk
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long msrl;
    @Column(nullable = false, unique = true, length = 30)
    private String uid;
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Column(nullable = false, length = 100)
    private String password;
    @Column(nullable = false, length = 100)
    private String name;

    @ElementCollection(fetch = FetchType.EAGER)
    @Builder.Default
    private List<String> roles = new ArrayList<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public String getUsername() {
        return this.uid;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Override
    public boolean isEnabled() {
        return true;
    }
}
  • Filter에서 예외 처리
    • Advice는 Spring이 처리 가능한 영역까지 도달해야 처리 가능
    • 그러나 SpringSecurity가 Spring 앞단에서 필터링하므로 처리 불가
  • 1. JWT에 문제가 있을 경우
    • 예시
      - JWT 없이 API 호출
      - JWT가 유효하지 않을 경우
    • 해결
      • SpringSecurity에서 제공하는 AuthenticationEntryPoint를 상속받아 재정의
      • 예외 발생시 /exception/entrypoint로 포워딩 처리
  • 2. 권한이 없을 경우
    • AccessDeniedHandler를 상속받아 재정의
    • /exception/accessdenied로 포워딩
// https://pythaac.notion.site/pythaac/Kwangmin-Koo-24c49fe713ce4cd2afe11c6d60d03f9d

package com.rest.api.config.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException,
            ServletException {
        response.sendRedirect("/exception/entrypoint");
    }
}
  • ExceptionController 작성
// https://daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/

package com.rest.api.controller.exception;

// import 생략

@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/exception")
public class ExceptionController {

    @GetMapping(value = "/entrypoint")
    public CommonResult entrypointException() {
        throw new CAuthenticationEntryPointException();
    }
}
  • 이 후 진행내용
    • Custion Exception(CAuthenticationEntryPointException)을 정의
    • MessageSource에 code/msg 추가
    • SpringSecurityConfiguration에 CustomAuthenticationEntryPoint 설정 추가
// https://daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/

@Override
protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic().disable() // rest api 이므로 기본설정 사용안함. 기본설정은 비인증시 로그인폼 화면으로 리다이렉트 된다.
            .csrf().disable() // rest api이므로 csrf 보안이 필요없으므로 disable처리.
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // jwt token으로 인증할것이므로 세션필요없으므로 생성안함.
            .and()
                .authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
                    .antMatchers("/*/signin", "/*/signup").permitAll() // 가입 및 인증 주소는 누구나 접근가능
                    .antMatchers(HttpMethod.GET, "/exception/**", "helloworld/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
                .anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
            .and()
                .exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
            .and()
                .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣어라.
}