Compare commits
15 Commits
feature/ap
...
feature/ju
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53da4ab810 | ||
|
|
d2a6c9bc81 | ||
|
|
e4d5cf3a77 | ||
|
|
ad6ab44345 | ||
|
|
02a4b3b7ea | ||
|
|
e163695ef6 | ||
|
|
b5157aa381 | ||
|
|
ee20205692 | ||
|
|
e663724567 | ||
|
|
73804c1189 | ||
|
|
12e462f022 | ||
|
|
41e93d885c | ||
|
|
8a58b45279 | ||
|
|
ffd8e8236d | ||
|
|
a7e3feb3bf |
65
README.md
Normal file
65
README.md
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
# Spring Rest Api 만들기 프로젝트
|
||||||
|
|
||||||
|
### 0. 개요
|
||||||
|
- SpringBoot2 framework 기반에서 RESTful api 서비스를 Step by Step으로 만들어 나가는 프로젝트
|
||||||
|
- daddyprogrammer.org에서 연재 및 소스 Github 등록
|
||||||
|
- https://daddyprogrammer.org/post/series/springboot2%EB%A1%9C-rest-api-%EB%A7%8C%EB%93%A4%EA%B8%B0/
|
||||||
|
|
||||||
|
### 1. 개발환경
|
||||||
|
- Java 8~11
|
||||||
|
- SpringBoot 2.x
|
||||||
|
- SpringSecurity 5.x
|
||||||
|
- JPA, H2
|
||||||
|
- Intellij Community
|
||||||
|
|
||||||
|
### 2. 프로젝트 실행
|
||||||
|
- H2 database 설치
|
||||||
|
- https://www.h2database.com/html/download.html
|
||||||
|
- intellij lombok 플러그인 설치
|
||||||
|
- Preferences -> Plugins -> Browse repositories... -> search lombok -> Install "IntelliJ Lombok plugin"
|
||||||
|
- Enable annotation processing
|
||||||
|
- Preferences - Annotation Procesors - Enable annotation processing 체크
|
||||||
|
- build.gradle에 lombok 추가(Git을 받은경우 이미 추가되어있음)
|
||||||
|
- compileOnly 'org.projectlombok:lombok:1.16.16'
|
||||||
|
- 실행
|
||||||
|
- Run -> SpringBootApiApplication
|
||||||
|
- Swagger
|
||||||
|
- http://localhost:8080/swagger-ui.html
|
||||||
|
|
||||||
|
### 3. 목차
|
||||||
|
- SpringBoot2로 Rest api 만들기(1) – Intellij Community에서 프로젝트생성
|
||||||
|
- Document
|
||||||
|
- https://daddyprogrammer.org/post/19/spring-boot1-start-intellij/
|
||||||
|
- SpringBoot2로 Rest api 만들기(2) – HelloWorld
|
||||||
|
- Document
|
||||||
|
- https://daddyprogrammer.org/post/41/spring-boot2-helloworld/
|
||||||
|
- SpringBoot2로 Rest api 만들기(3) – H2 Database 연동
|
||||||
|
- Document
|
||||||
|
- https://daddyprogrammer.org/post/152/spring-boot2-h2-database-intergrate/
|
||||||
|
- Git
|
||||||
|
- https://github.com/codej99/SpringRestApi/tree/feature/h2
|
||||||
|
- SpringBoot2로 Rest api 만들기(4) – Swagger API 문서 자동화
|
||||||
|
- Document
|
||||||
|
- https://daddyprogrammer.org/post/313/swagger-api-doc/
|
||||||
|
- Git
|
||||||
|
- https://github.com/codej99/SpringRestApi/tree/feature/swagger
|
||||||
|
- SpringBoot2로 Rest api 만들기(5) – API 인터페이스 및 결과 데이터 구조 설계
|
||||||
|
- Document
|
||||||
|
- https://daddyprogrammer.org/post/404/spring-boot2-5-design-api-interface-and-data-structure/
|
||||||
|
- Git
|
||||||
|
- https://github.com/codej99/SpringRestApi/tree/feature/api-structure
|
||||||
|
- SpringBoot2로 Rest api 만들기(6) – ControllerAdvice를 이용한 Exception처리
|
||||||
|
- Document
|
||||||
|
- https://daddyprogrammer.org/post/446/spring-boot2-5-exception-handling/
|
||||||
|
- Git
|
||||||
|
- https://github.com/codej99/SpringRestApi/tree/feature/controller-advice
|
||||||
|
- SpringBoot2로 Rest api 만들기(7) – MessageSource를 이용한 Exception 처리
|
||||||
|
- Document
|
||||||
|
- https://daddyprogrammer.org/post/499/springboot2-message-exception-handling-with-controlleradvice/
|
||||||
|
- Git
|
||||||
|
- https://github.com/codej99/SpringRestApi/tree/feature/messagesource
|
||||||
|
- SpringBoot2로 Rest api 만들기(8) – SpringSecurity를 이용한 인증 및 권한부여
|
||||||
|
- Document
|
||||||
|
- https://daddyprogrammer.org/post/636/springboot2-springsecurity-authentication-authorization/
|
||||||
|
- Git
|
||||||
|
- https://github.com/codej99/SpringRestApi/tree/feature/security
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
plugins {
|
plugins {
|
||||||
id 'org.springframework.boot' version '2.1.4.RELEASE'
|
id 'org.springframework.boot' version '2.1.4.RELEASE'
|
||||||
id 'java'
|
id 'java'
|
||||||
|
id "org.sonarqube" version "2.7"
|
||||||
}
|
}
|
||||||
|
|
||||||
apply plugin: 'io.spring.dependency-management'
|
apply plugin: 'io.spring.dependency-management'
|
||||||
@@ -23,11 +24,15 @@ dependencies {
|
|||||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
|
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||||
|
implementation 'io.jsonwebtoken:jjwt:0.9.1'
|
||||||
implementation 'io.springfox:springfox-swagger2:2.6.1'
|
implementation 'io.springfox:springfox-swagger2:2.6.1'
|
||||||
implementation 'io.springfox:springfox-swagger-ui:2.6.1'
|
implementation 'io.springfox:springfox-swagger-ui:2.6.1'
|
||||||
|
implementation 'net.rakugakibox.util:yaml-resource-bundle:1.1'
|
||||||
compileOnly 'org.projectlombok:lombok'
|
compileOnly 'org.projectlombok:lombok'
|
||||||
runtimeOnly 'com.h2database:h2'
|
runtimeOnly 'com.h2database:h2'
|
||||||
runtimeOnly 'mysql:mysql-connector-java'
|
runtimeOnly 'mysql:mysql-connector-java'
|
||||||
annotationProcessor 'org.projectlombok:lombok'
|
annotationProcessor 'org.projectlombok:lombok'
|
||||||
|
testImplementation 'org.springframework.security:spring-security-test'
|
||||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,18 @@ package com.rest.api;
|
|||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class SpringRestApiApplication {
|
public class SpringRestApiApplication {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(SpringRestApiApplication.class, args);
|
SpringApplication.run(SpringRestApiApplication.class, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public PasswordEncoder passwordEncoder() {
|
||||||
|
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
66
src/main/java/com/rest/api/advice/ExceptionAdvice.java
Normal file
66
src/main/java/com/rest/api/advice/ExceptionAdvice.java
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
package com.rest.api.advice;
|
||||||
|
|
||||||
|
import com.rest.api.advice.exception.CAuthenticationEntryPointException;
|
||||||
|
import com.rest.api.advice.exception.CEmailSigninFailedException;
|
||||||
|
import com.rest.api.advice.exception.CUserNotFoundException;
|
||||||
|
import com.rest.api.model.response.CommonResult;
|
||||||
|
import com.rest.api.service.ResponseService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.context.MessageSource;
|
||||||
|
import org.springframework.context.i18n.LocaleContextHolder;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
|
@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 userNotFound(HttpServletRequest request, CUserNotFoundException e) {
|
||||||
|
return responseService.getFailResult(Integer.valueOf(getMessage("userNotFound.code")), getMessage("userNotFound.msg"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(CEmailSigninFailedException.class)
|
||||||
|
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
|
protected CommonResult emailSigninFailed(HttpServletRequest request, CEmailSigninFailedException e) {
|
||||||
|
return responseService.getFailResult(Integer.valueOf(getMessage("emailSigninFailed.code")), getMessage("emailSigninFailed.msg"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(CAuthenticationEntryPointException.class)
|
||||||
|
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||||
|
public CommonResult authenticationEntryPointException(HttpServletRequest request, CAuthenticationEntryPointException e) {
|
||||||
|
return responseService.getFailResult(Integer.valueOf(getMessage("entryPointException.code")), getMessage("entryPointException.msg"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(AccessDeniedException.class)
|
||||||
|
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||||
|
public CommonResult accessDeniedException(HttpServletRequest request, AccessDeniedException e) {
|
||||||
|
return responseService.getFailResult(Integer.valueOf(getMessage("accessDenied.code")), getMessage("accessDenied.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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.rest.api.advice.exception;
|
||||||
|
|
||||||
|
public class CAuthenticationEntryPointException extends RuntimeException {
|
||||||
|
public CAuthenticationEntryPointException(String msg, Throwable t) {
|
||||||
|
super(msg, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CAuthenticationEntryPointException(String msg) {
|
||||||
|
super(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CAuthenticationEntryPointException() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.rest.api.advice.exception;
|
||||||
|
|
||||||
|
public class CEmailSigninFailedException extends RuntimeException {
|
||||||
|
public CEmailSigninFailedException(String msg, Throwable t) {
|
||||||
|
super(msg, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CEmailSigninFailedException(String msg) {
|
||||||
|
super(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CEmailSigninFailedException() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.rest.api.advice.exception;
|
||||||
|
|
||||||
|
public class CUserNotFoundException extends RuntimeException {
|
||||||
|
public CUserNotFoundException(String msg, Throwable t) {
|
||||||
|
super(msg, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CUserNotFoundException(String msg) {
|
||||||
|
super(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CUserNotFoundException() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
61
src/main/java/com/rest/api/config/MessageConfiguration.java
Normal file
61
src/main/java/com/rest/api/config/MessageConfiguration.java
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package com.rest.api.config;
|
||||||
|
|
||||||
|
import net.rakugakibox.util.YamlResourceBundle;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.MessageSource;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.support.ResourceBundleMessageSource;
|
||||||
|
import org.springframework.web.servlet.LocaleResolver;
|
||||||
|
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||||
|
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.ResourceBundle;
|
||||||
|
|
||||||
|
@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) {
|
||||||
|
return ResourceBundle.getBundle(basename, locale, YamlResourceBundle.Control.INSTANCE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,7 +17,7 @@ public class SwaggerConfiguration {
|
|||||||
public Docket swaggerApi() {
|
public Docket swaggerApi() {
|
||||||
return new Docket(DocumentationType.SWAGGER_2).apiInfo(swaggerInfo()).select()
|
return new Docket(DocumentationType.SWAGGER_2).apiInfo(swaggerInfo()).select()
|
||||||
.apis(RequestHandlerSelectors.basePackage("com.rest.api.controller"))
|
.apis(RequestHandlerSelectors.basePackage("com.rest.api.controller"))
|
||||||
.paths(PathSelectors.any())
|
.paths(PathSelectors.ant("/v1/**"))
|
||||||
.build()
|
.build()
|
||||||
.useDefaultResponseMessages(false); // 기본으로 세팅되는 200,401,403,404 메시지를 표시 하지 않음
|
.useDefaultResponseMessages(false); // 기본으로 세팅되는 200,401,403,404 메시지를 표시 하지 않음
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.rest.api.config.security;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||||
|
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 CustomAccessDeniedHandler implements AccessDeniedHandler {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException,
|
||||||
|
ServletException {
|
||||||
|
RequestDispatcher dispatcher = request.getRequestDispatcher("/exception/accessdenied");
|
||||||
|
dispatcher.forward(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
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 {
|
||||||
|
RequestDispatcher dispatcher = request.getRequestDispatcher("/exception/entrypoint");
|
||||||
|
dispatcher.forward(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.rest.api.config.security;
|
||||||
|
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.web.filter.GenericFilterBean;
|
||||||
|
|
||||||
|
import javax.servlet.FilterChain;
|
||||||
|
import javax.servlet.ServletException;
|
||||||
|
import javax.servlet.ServletRequest;
|
||||||
|
import javax.servlet.ServletResponse;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package com.rest.api.config.security;
|
||||||
|
|
||||||
|
import io.jsonwebtoken.Claims;
|
||||||
|
import io.jsonwebtoken.Jws;
|
||||||
|
import io.jsonwebtoken.Jwts;
|
||||||
|
import io.jsonwebtoken.SignatureAlgorithm;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.rest.api.config.security;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
|
|
||||||
|
@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/**", "/favicon.ico").permitAll() // 등록한 GET요청 리소스는 누구나 접근가능
|
||||||
|
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
|
||||||
|
.and()
|
||||||
|
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())
|
||||||
|
.and()
|
||||||
|
.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
|
||||||
|
.and()
|
||||||
|
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // jwt token 필터를 id/password 인증 필터 전에 넣어라.
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override // ignore swagger security config
|
||||||
|
public void configure(WebSecurity web) {
|
||||||
|
web.ignoring().antMatchers("/v2/api-docs", "/swagger-resources/**",
|
||||||
|
"/swagger-ui.html", "/webjars/**", "/swagger/**");
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,23 +9,25 @@ import org.springframework.web.bind.annotation.ResponseBody;
|
|||||||
@Controller
|
@Controller
|
||||||
public class HelloController {
|
public class HelloController {
|
||||||
|
|
||||||
|
private static final String HELLO = "helloworld";
|
||||||
|
|
||||||
@Setter
|
@Setter
|
||||||
@Getter
|
@Getter
|
||||||
public static class Hello {
|
private static class Hello {
|
||||||
private String message;
|
private String message;
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping(value = "/helloworld/string")
|
@GetMapping(value = "/helloworld/string")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public String helloworldString() {
|
public String helloworldString() {
|
||||||
return "helloworld";
|
return HELLO;
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping(value = "/helloworld/json")
|
@GetMapping(value = "/helloworld/json")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Hello helloworldJson() {
|
public Hello helloworldJson() {
|
||||||
Hello hello = new Hello();
|
Hello hello = new Hello();
|
||||||
hello.message = "helloworld";
|
hello.message = HELLO;
|
||||||
return hello;
|
return hello;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.rest.api.controller.exception;
|
||||||
|
|
||||||
|
import com.rest.api.advice.exception.CAuthenticationEntryPointException;
|
||||||
|
import com.rest.api.model.response.CommonResult;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@RestController
|
||||||
|
@RequestMapping(value = "/exception")
|
||||||
|
public class ExceptionController {
|
||||||
|
|
||||||
|
@GetMapping(value = "/entrypoint")
|
||||||
|
public CommonResult entrypointException() {
|
||||||
|
throw new CAuthenticationEntryPointException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(value = "/accessdenied")
|
||||||
|
public CommonResult accessdeniedException() {
|
||||||
|
throw new AccessDeniedException("");
|
||||||
|
}
|
||||||
|
}
|
||||||
56
src/main/java/com/rest/api/controller/v1/SignController.java
Normal file
56
src/main/java/com/rest/api/controller/v1/SignController.java
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package com.rest.api.controller.v1;
|
||||||
|
|
||||||
|
import com.rest.api.advice.exception.CEmailSigninFailedException;
|
||||||
|
import com.rest.api.entity.User;
|
||||||
|
import com.rest.api.config.security.JwtTokenProvider;
|
||||||
|
import com.rest.api.model.response.CommonResult;
|
||||||
|
import com.rest.api.model.response.SingleResult;
|
||||||
|
import com.rest.api.repo.UserJpaRepo;
|
||||||
|
import com.rest.api.service.ResponseService;
|
||||||
|
import io.swagger.annotations.Api;
|
||||||
|
import io.swagger.annotations.ApiOperation;
|
||||||
|
import io.swagger.annotations.ApiParam;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
@Api(tags = {"1. Sign"})
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@RestController
|
||||||
|
@RequestMapping(value = "/v1")
|
||||||
|
public class SignController {
|
||||||
|
|
||||||
|
private final UserJpaRepo userJpaRepo;
|
||||||
|
private final JwtTokenProvider jwtTokenProvider;
|
||||||
|
private final ResponseService responseService;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
@ApiOperation(value = "로그인", notes = "이메일 회원 로그인을 한다.")
|
||||||
|
@PostMapping(value = "/signin")
|
||||||
|
public SingleResult<String> signin(@ApiParam(value = "회원ID : 이메일", required = true) @RequestParam String id,
|
||||||
|
@ApiParam(value = "비밀번호", required = true) @RequestParam String password) {
|
||||||
|
|
||||||
|
User user = userJpaRepo.findByUid(id).orElseThrow(CEmailSigninFailedException::new);
|
||||||
|
if (!passwordEncoder.matches(password, user.getPassword()))
|
||||||
|
throw new CEmailSigninFailedException();
|
||||||
|
|
||||||
|
return responseService.getSingleResult(jwtTokenProvider.createToken(String.valueOf(user.getMsrl()), user.getRoles()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation(value = "가입", notes = "회원가입을 한다.")
|
||||||
|
@PostMapping(value = "/signup")
|
||||||
|
public CommonResult signup(@ApiParam(value = "회원ID : 이메일", required = true) @RequestParam String id,
|
||||||
|
@ApiParam(value = "비밀번호", required = true) @RequestParam String password,
|
||||||
|
@ApiParam(value = "이름", required = true) @RequestParam String name) {
|
||||||
|
|
||||||
|
userJpaRepo.save(User.builder()
|
||||||
|
.uid(id)
|
||||||
|
.password(passwordEncoder.encode(password))
|
||||||
|
.name(name)
|
||||||
|
.roles(Collections.singletonList("ROLE_USER"))
|
||||||
|
.build());
|
||||||
|
return responseService.getSuccessResult();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +1,19 @@
|
|||||||
package com.rest.api.controller.v1;
|
package com.rest.api.controller.v1;
|
||||||
|
|
||||||
|
import com.rest.api.advice.exception.CUserNotFoundException;
|
||||||
import com.rest.api.entity.User;
|
import com.rest.api.entity.User;
|
||||||
import com.rest.api.model.response.CommonResult;
|
import com.rest.api.model.response.CommonResult;
|
||||||
import com.rest.api.model.response.ListResult;
|
import com.rest.api.model.response.ListResult;
|
||||||
import com.rest.api.model.response.SingleResult;
|
import com.rest.api.model.response.SingleResult;
|
||||||
import com.rest.api.repo.UserJpaRepo;
|
import com.rest.api.repo.UserJpaRepo;
|
||||||
import com.rest.api.service.ResponseService;
|
import com.rest.api.service.ResponseService;
|
||||||
import io.swagger.annotations.Api;
|
import io.swagger.annotations.*;
|
||||||
import io.swagger.annotations.ApiOperation;
|
|
||||||
import io.swagger.annotations.ApiParam;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
@Api(tags = {"1. User"})
|
@Api(tags = {"2. User"})
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping(value = "/v1")
|
@RequestMapping(value = "/v1")
|
||||||
@@ -21,6 +22,9 @@ public class UserController {
|
|||||||
private final UserJpaRepo userJpaRepo;
|
private final UserJpaRepo userJpaRepo;
|
||||||
private final ResponseService responseService; // 결과를 처리할 Service
|
private final ResponseService responseService; // 결과를 처리할 Service
|
||||||
|
|
||||||
|
@ApiImplicitParams({
|
||||||
|
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||||
|
})
|
||||||
@ApiOperation(value = "회원 리스트 조회", notes = "모든 회원을 조회한다")
|
@ApiOperation(value = "회원 리스트 조회", notes = "모든 회원을 조회한다")
|
||||||
@GetMapping(value = "/users")
|
@GetMapping(value = "/users")
|
||||||
public ListResult<User> findAllUser() {
|
public ListResult<User> findAllUser() {
|
||||||
@@ -28,39 +32,38 @@ public class UserController {
|
|||||||
return responseService.getListResult(userJpaRepo.findAll());
|
return responseService.getListResult(userJpaRepo.findAll());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ApiOperation(value = "회원 단건 조회", notes = "userId로 회원을 조회한다")
|
@ApiImplicitParams({
|
||||||
@GetMapping(value = "/user/{msrl}")
|
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||||
public SingleResult<User> findUserById(@ApiParam(value = "회원ID", required = true) @PathVariable long msrl) {
|
})
|
||||||
// 결과데이터가 단일건인경우 getBasicResult를 이용해서 결과를 출력한다.
|
@ApiOperation(value = "회원 단건 조회", notes = "회원번호(msrl)로 회원을 조회한다")
|
||||||
return responseService.getSingleResult(userJpaRepo.findById(msrl).orElse(null));
|
@GetMapping(value = "/user")
|
||||||
}
|
public SingleResult<User> findUser() {
|
||||||
|
// SecurityContext에서 인증받은 회원의 정보를 얻어온다.
|
||||||
@ApiOperation(value = "회원 입력", notes = "회원을 입력한다")
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||||
@PostMapping(value = "/user")
|
String id = authentication.getName();
|
||||||
public SingleResult<User> save(@ApiParam(value = "회원아이디", required = true) @RequestParam String uid,
|
// 결과데이터가 단일건인경우 getSingleResult를 이용해서 결과를 출력한다.
|
||||||
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
|
return responseService.getSingleResult(userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new));
|
||||||
User user = User.builder()
|
|
||||||
.uid(uid)
|
|
||||||
.name(name)
|
|
||||||
.build();
|
|
||||||
return responseService.getSingleResult(userJpaRepo.save(user));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ApiImplicitParams({
|
||||||
|
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||||
|
})
|
||||||
@ApiOperation(value = "회원 수정", notes = "회원정보를 수정한다")
|
@ApiOperation(value = "회원 수정", notes = "회원정보를 수정한다")
|
||||||
@PutMapping(value = "/user")
|
@PutMapping(value = "/user")
|
||||||
public SingleResult<User> modify(
|
public SingleResult<User> modify(
|
||||||
@ApiParam(value = "회원번호", required = true) @RequestParam long msrl,
|
@ApiParam(value = "회원번호", required = true) @RequestParam long msrl,
|
||||||
@ApiParam(value = "회원아이디", required = true) @RequestParam String uid,
|
|
||||||
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
|
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
|
||||||
User user = User.builder()
|
User user = User.builder()
|
||||||
.msrl(msrl)
|
.msrl(msrl)
|
||||||
.uid(uid)
|
|
||||||
.name(name)
|
.name(name)
|
||||||
.build();
|
.build();
|
||||||
return responseService.getSingleResult(userJpaRepo.save(user));
|
return responseService.getSingleResult(userJpaRepo.save(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ApiOperation(value = "회원 삭제", notes = "userId로 회원정보를 삭제한다")
|
@ApiImplicitParams({
|
||||||
|
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||||
|
})
|
||||||
|
@ApiOperation(value = "회원 삭제", notes = "회원번호(msrl)로 회원정보를 삭제한다")
|
||||||
@DeleteMapping(value = "/user/{msrl}")
|
@DeleteMapping(value = "/user/{msrl}")
|
||||||
public CommonResult delete(
|
public CommonResult delete(
|
||||||
@ApiParam(value = "회원번호", required = true) @PathVariable long msrl) {
|
@ApiParam(value = "회원번호", required = true) @PathVariable long msrl) {
|
||||||
@@ -69,3 +72,4 @@ public class UserController {
|
|||||||
return responseService.getSuccessResult();
|
return responseService.getSuccessResult();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,19 @@
|
|||||||
package com.rest.api.entity;
|
package com.rest.api.entity;
|
||||||
|
|
||||||
import lombok.*;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
|
||||||
import javax.persistence.*;
|
import javax.persistence.*;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@Builder // builder를 사용할수 있게 합니다.
|
@Builder // builder를 사용할수 있게 합니다.
|
||||||
@Entity // jpa entity임을 알립니다.
|
@Entity // jpa entity임을 알립니다.
|
||||||
@@ -10,13 +21,54 @@ import javax.persistence.*;
|
|||||||
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
|
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
|
||||||
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
|
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
|
||||||
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
|
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
|
||||||
public class User {
|
public class User implements UserDetails {
|
||||||
@Id // primaryKey임을 알립니다.
|
@Id // pk
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
// pk생성전략을 DB에 위임한다는 의미입니다. mysql로 보면 pk 필드를 auto_increment로 설정해 놓은 경우로 보면 됩니다.
|
|
||||||
private long msrl;
|
private long msrl;
|
||||||
@Column(nullable = false, unique = true, length = 30) // uid column을 명시합니다. 필수이고 유니크한 필드이며 길이는 30입니다.
|
@Column(nullable = false, unique = true, length = 50)
|
||||||
private String uid;
|
private String uid;
|
||||||
@Column(nullable = false, length = 100) // name column을 명시합니다. 필수이고 길이는 100입니다.
|
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||||
|
@Column(nullable = false, length = 100)
|
||||||
|
private String password;
|
||||||
|
@Column(nullable = false, length = 100)
|
||||||
private String name;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ package com.rest.api.repo;
|
|||||||
|
|
||||||
import com.rest.api.entity.User;
|
import com.rest.api.entity.User;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
public interface UserJpaRepo extends JpaRepository<User, Long> {
|
public interface UserJpaRepo extends JpaRepository<User, Long> {
|
||||||
|
|
||||||
|
Optional<User> findByUid(String email);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,13 +7,12 @@ import org.springframework.stereotype.Service;
|
|||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Service // 해당 Class가 Service임을 명시합니다.
|
@Service
|
||||||
public class ResponseService {
|
public class ResponseService {
|
||||||
|
|
||||||
// enum으로 api 요청 결과에 대한 code, message를 정의합니다.
|
// enum으로 api 요청 결과에 대한 code, message를 정의합니다.
|
||||||
public enum CommonResponse {
|
public enum CommonResponse {
|
||||||
SUCCESS(0, "성공하였습니디."),
|
SUCCESS(0, "성공하였습니다.");
|
||||||
FAIL(-1, "실패하였습니다.");
|
|
||||||
|
|
||||||
int code;
|
int code;
|
||||||
String msg;
|
String msg;
|
||||||
@@ -52,11 +51,11 @@ public class ResponseService {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
// 실패 결과만 처리하는 메소드
|
// 실패 결과만 처리하는 메소드
|
||||||
public CommonResult getFailResult() {
|
public CommonResult getFailResult(int code, String msg) {
|
||||||
CommonResult result = new CommonResult();
|
CommonResult result = new CommonResult();
|
||||||
result.setSuccess(false);
|
result.setSuccess(false);
|
||||||
result.setCode(CommonResponse.FAIL.getCode());
|
result.setCode(code);
|
||||||
result.setMsg(CommonResponse.FAIL.getMsg());
|
result.setMsg(msg);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
// 결과 모델에 api 요청 성공 데이터를 세팅해주는 메소드
|
// 결과 모델에 api 요청 성공 데이터를 세팅해주는 메소드
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.rest.api.service.security;
|
||||||
|
|
||||||
|
import com.rest.api.advice.exception.CUserNotFoundException;
|
||||||
|
import com.rest.api.repo.UserJpaRepo;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,4 +9,9 @@ spring:
|
|||||||
jpa:
|
jpa:
|
||||||
database-platform: org.hibernate.dialect.H2Dialect
|
database-platform: org.hibernate.dialect.H2Dialect
|
||||||
properties.hibernate.hbm2ddl.auto: update
|
properties.hibernate.hbm2ddl.auto: update
|
||||||
showSql: true
|
showSql: true
|
||||||
|
messages:
|
||||||
|
basename: i18n/exception
|
||||||
|
encoding: UTF-8
|
||||||
|
jwt:
|
||||||
|
secret: govlepel@$&
|
||||||
15
src/main/resources/i18n/exception_en.yml
Normal file
15
src/main/resources/i18n/exception_en.yml
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
unKnown:
|
||||||
|
code: "-9999"
|
||||||
|
msg: "An unknown error has occurred."
|
||||||
|
userNotFound:
|
||||||
|
code: "-1000"
|
||||||
|
msg: "This member not exist"
|
||||||
|
emailSigninFailed:
|
||||||
|
code: "-1001"
|
||||||
|
msg: "Your account does not exist or your email or password is incorrect."
|
||||||
|
entryPointException:
|
||||||
|
code: "-1002"
|
||||||
|
msg: "You do not have permission to access this resource."
|
||||||
|
accessDenied:
|
||||||
|
code: "-1003"
|
||||||
|
msg: "A resource that can not be accessed with the privileges it has."
|
||||||
15
src/main/resources/i18n/exception_ko.yml
Normal file
15
src/main/resources/i18n/exception_ko.yml
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
unKnown:
|
||||||
|
code: "-9999"
|
||||||
|
msg: "알수 없는 오류가 발생하였습니다."
|
||||||
|
userNotFound:
|
||||||
|
code: "-1000"
|
||||||
|
msg: "존재하지 않는 회원입니다."
|
||||||
|
emailSigninFailed:
|
||||||
|
code: "-1001"
|
||||||
|
msg: "계정이 존재하지 않거나 이메일 또는 비밀번호가 정확하지 않습니다."
|
||||||
|
entryPointException:
|
||||||
|
code: "-1002"
|
||||||
|
msg: "해당 리소스에 접근하기 위한 권한이 없습니다."
|
||||||
|
accessDenied:
|
||||||
|
code: "-1003"
|
||||||
|
msg: "보유한 권한으로 접근할수 없는 리소스 입니다."
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
package com.rest.api;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
|
||||||
@SpringBootTest
|
|
||||||
public class SpringRestApiApplicationTests {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void contextLoads() {
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.rest.api.controller;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest
|
||||||
|
@AutoConfigureMockMvc
|
||||||
|
@Transactional
|
||||||
|
public class HelloControllerTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MockMvc mockMvc;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void helloworldString() throws Exception {
|
||||||
|
mockMvc.perform(get("/helloworld/string"))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(content().contentType("text/plain;charset=UTF-8"))
|
||||||
|
.andExpect(content().string("helloworld"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void helloworldJson() throws Exception {
|
||||||
|
mockMvc.perform(get("/helloworld/json"))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(content().contentType("application/json;charset=utf-8"))
|
||||||
|
.andExpect(jsonPath("$.message").value("helloworld"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void helloworldPage() throws Exception {
|
||||||
|
mockMvc.perform(get("/helloworld/page"))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(content().contentType("text/html;charset=UTF-8"))
|
||||||
|
.andExpect(view().name("helloworld"))
|
||||||
|
.andExpect(content().string("helloworld"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package com.rest.api.controller.v1;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.LinkedMultiValueMap;
|
||||||
|
import org.springframework.util.MultiValueMap;
|
||||||
|
import org.springframework.web.context.WebApplicationContext;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest
|
||||||
|
@AutoConfigureMockMvc
|
||||||
|
@Transactional
|
||||||
|
public class SignControllerTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MockMvc mockMvc;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void signin() throws Exception {
|
||||||
|
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||||
|
params.add("id", "happydaddy@naver.com");
|
||||||
|
params.add("password", "1234");
|
||||||
|
mockMvc.perform(post("/v1/signin").params(params))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.success").value(true))
|
||||||
|
.andExpect(jsonPath("$.code").value(0))
|
||||||
|
.andExpect(jsonPath("$.msg").exists())
|
||||||
|
.andExpect(jsonPath("$.data").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void signinFail() throws Exception {
|
||||||
|
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||||
|
params.add("id", "happydaddy@naver.com");
|
||||||
|
params.add("password", "12345");
|
||||||
|
mockMvc.perform(post("/v1/signin").params(params))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().is5xxServerError())
|
||||||
|
.andExpect(jsonPath("$.success").value(false))
|
||||||
|
.andExpect(jsonPath("$.code").value(-1001))
|
||||||
|
.andExpect(jsonPath("$.msg").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void signup() throws Exception {
|
||||||
|
long epochTime = LocalDateTime.now().atZone(ZoneId.systemDefault()).toEpochSecond();
|
||||||
|
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||||
|
params.add("id", "happydaddy_" + epochTime + "@naver.com");
|
||||||
|
params.add("password", "12345");
|
||||||
|
params.add("name", "happydaddy_" + epochTime);
|
||||||
|
mockMvc.perform(post("/v1/signup").params(params))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.success").value(true))
|
||||||
|
.andExpect(jsonPath("$.code").value(0))
|
||||||
|
.andExpect(jsonPath("$.msg").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void signupFail() throws Exception {
|
||||||
|
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||||
|
params.add("id", "happydaddy@naver.com");
|
||||||
|
params.add("password", "12345");
|
||||||
|
params.add("name", "happydaddy");
|
||||||
|
mockMvc.perform(post("/v1/signup").params(params))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().is5xxServerError())
|
||||||
|
.andExpect(jsonPath("$.success").value(false))
|
||||||
|
.andExpect(jsonPath("$.code").value(-9999));
|
||||||
|
}
|
||||||
|
}
|
||||||
119
src/test/java/com/rest/api/controller/v1/UserControllerTest.java
Normal file
119
src/test/java/com/rest/api/controller/v1/UserControllerTest.java
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
package com.rest.api.controller.v1;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.json.JacksonJsonParser;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.security.test.context.support.WithMockUser;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.MvcResult;
|
||||||
|
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.LinkedMultiValueMap;
|
||||||
|
import org.springframework.util.MultiValueMap;
|
||||||
|
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest
|
||||||
|
@AutoConfigureMockMvc
|
||||||
|
@Transactional
|
||||||
|
public class UserControllerTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MockMvc mockMvc;
|
||||||
|
|
||||||
|
private String token;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||||
|
params.add("id", "happydaddy@naver.com");
|
||||||
|
params.add("password", "1234");
|
||||||
|
MvcResult result = mockMvc.perform(post("/v1/signin").params(params))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.success").value(true))
|
||||||
|
.andExpect(jsonPath("$.code").value(0))
|
||||||
|
.andExpect(jsonPath("$.msg").exists())
|
||||||
|
.andExpect(jsonPath("$.data").exists())
|
||||||
|
.andReturn();
|
||||||
|
|
||||||
|
String resultString = result.getResponse().getContentAsString();
|
||||||
|
JacksonJsonParser jsonParser = new JacksonJsonParser();
|
||||||
|
token = jsonParser.parseMap(resultString).get("data").toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void invalidToken() throws Exception {
|
||||||
|
mockMvc.perform(MockMvcRequestBuilders
|
||||||
|
.get("/v1/users")
|
||||||
|
.header("X-AUTH-TOKEN", "XXXXXXXXXX"))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(forwardedUrl("/exception/entrypoint"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "mockUser", roles = {"ADMIN"}) // 가상의 Mock 유저 대입
|
||||||
|
public void accessdenied() throws Exception {
|
||||||
|
mockMvc.perform(MockMvcRequestBuilders
|
||||||
|
.get("/v1/users"))
|
||||||
|
//.header("X-AUTH-TOKEN", token))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(forwardedUrl("/exception/accessdenied"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void findAllUser() throws Exception {
|
||||||
|
mockMvc.perform(MockMvcRequestBuilders
|
||||||
|
.get("/v1/users")
|
||||||
|
.header("X-AUTH-TOKEN", token))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.success").value(true))
|
||||||
|
.andExpect(jsonPath("$.list").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void findUser() throws Exception {
|
||||||
|
mockMvc.perform(MockMvcRequestBuilders
|
||||||
|
.get("/v1/user")
|
||||||
|
.header("X-AUTH-TOKEN", token))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.success").value(true))
|
||||||
|
.andExpect(jsonPath("$.data").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void modify() throws Exception {
|
||||||
|
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||||
|
params.add("msrl", "1");
|
||||||
|
params.add("name", "행복전도사");
|
||||||
|
mockMvc.perform(MockMvcRequestBuilders
|
||||||
|
.put("/v1/user")
|
||||||
|
.header("X-AUTH-TOKEN", token)
|
||||||
|
.params(params))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.success").value(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void delete() throws Exception {
|
||||||
|
mockMvc.perform(MockMvcRequestBuilders
|
||||||
|
.delete("/v1/user/2")
|
||||||
|
.header("X-AUTH-TOKEN", token))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.success").value(true));
|
||||||
|
}
|
||||||
|
}
|
||||||
46
src/test/java/com/rest/api/repo/UserJpaRepoTest.java
Normal file
46
src/test/java/com/rest/api/repo/UserJpaRepoTest.java
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package com.rest.api.repo;
|
||||||
|
|
||||||
|
import com.rest.api.entity.User;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.is;
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@DataJpaTest
|
||||||
|
public class UserJpaRepoTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private UserJpaRepo userJpaRepo;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindByUid_thenReturnUser() {
|
||||||
|
String uid = "angrydaddy@gmail.com";
|
||||||
|
String name = "angrydaddy";
|
||||||
|
// given
|
||||||
|
userJpaRepo.save(User.builder()
|
||||||
|
.uid(uid)
|
||||||
|
.password(passwordEncoder.encode("1234"))
|
||||||
|
.name(name)
|
||||||
|
.roles(Collections.singletonList("ROLE_USER"))
|
||||||
|
.build());
|
||||||
|
// when
|
||||||
|
Optional<User> user = userJpaRepo.findByUid(uid);
|
||||||
|
// then
|
||||||
|
assertNotNull(user);// user객체가 null이 아닌지 체크
|
||||||
|
assertTrue(user.isPresent()); // user객체가 존재여부 true/false 체크
|
||||||
|
assertEquals(user.get().getName(), name); // user객체의 name과 name변수 값이 같은지 체크
|
||||||
|
assertThat(user.get().getName(), is(name)); // user객체의 name과 name변수 값이 같은지 체크
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user