14 Commits

Author SHA1 Message Date
kimyonghwa
53da4ab810 bugfix
- update ftl path
- delete duplicate security settings
2019-11-14 11:39:46 +09:00
kimyonghwa
d2a6c9bc81 SpringBoot2로 Rest api 만들기(9) – Unit Test 2019-04-18 15:20:56 +09:00
kimyonghwa
e4d5cf3a77 Spring Unit Test 2019-04-17 19:24:09 +09:00
codej99
ad6ab44345 Merge pull request #5 from codej99/feature/sonarqube
Modify sonarqube analysis
2019-04-17 11:00:35 +09:00
kimyonghwa
02a4b3b7ea Modify sonarqube analysis 2019-04-17 10:57:10 +09:00
codej99
e163695ef6 Merge pull request #4 from codej99/feature/readme.md
Create README.md
2019-04-16 17:06:10 +09:00
kimyonghwa
b5157aa381 Create README.md 2019-04-16 17:05:35 +09:00
codej99
ee20205692 Merge pull request #3 from codej99/feature/readme.md
Create README.md
2019-04-16 17:04:55 +09:00
kimyonghwa
e663724567 Create README.md 2019-04-16 17:04:23 +09:00
codej99
73804c1189 Merge pull request #2 from codej99/feature/security
SpringBoot2로 Rest api 만들기(8) –  SpringSecurity를 이용한 인증 및 권한부여
2019-04-16 16:24:22 +09:00
codej99
12e462f022 Merge branch 'master' into feature/security 2019-04-16 16:24:10 +09:00
kimyonghwa
41e93d885c SpringBoot2로 Rest api 만들기(8) – SpringSecurity를 이용한 인증 및 권한부여 2019-04-16 15:54:37 +09:00
codej99
8a58b45279 Merge pull request #1 from codej99/feature/messagesource
SpringBoot2로 Rest api 만들기(7) –  MessageSource를 이용한 Exception 처리
2019-04-16 10:54:18 +09:00
kimyonghwa
a7e3feb3bf SpringBoot2로 Rest api 만들기(8) – SpringSecurity를 이용한 api 인증 및 권한부여 2019-04-15 19:14:45 +09:00
29 changed files with 860 additions and 59 deletions

65
README.md Normal file
View 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

View File

@@ -1,6 +1,7 @@
plugins {
id 'org.springframework.boot' version '2.1.4.RELEASE'
id 'java'
id "org.sonarqube" version "2.7"
}
apply plugin: 'io.spring.dependency-management'
@@ -23,6 +24,8 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
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-swagger-ui:2.6.1'
implementation 'net.rakugakibox.util:yaml-resource-bundle:1.1'
@@ -30,5 +33,6 @@ dependencies {
runtimeOnly 'com.h2database:h2'
runtimeOnly 'mysql:mysql-connector-java'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

View File

@@ -2,10 +2,18 @@ package com.rest.api;
import org.springframework.boot.SpringApplication;
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
public class SpringRestApiApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRestApiApplication.class, args);
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}

View File

@@ -1,5 +1,7 @@
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;
@@ -7,6 +9,7 @@ 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;
@@ -30,11 +33,28 @@ public class ExceptionAdvice {
@ExceptionHandler(CUserNotFoundException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult userNotFoundException(HttpServletRequest request, CUserNotFoundException e) {
// 예외 처리의 메시지를 MessageSource에서 가져오도록 수정
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);

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -1,6 +1,5 @@
package com.rest.api.config;
import lombok.extern.slf4j.Slf4j;
import net.rakugakibox.util.YamlResourceBundle;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
@@ -14,7 +13,6 @@ import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
@Configuration
@@ -56,7 +54,7 @@ public class MessageConfiguration implements WebMvcConfigurer {
// locale 정보에 따라 다른 yml 파일을 읽도록 처리
private static class YamlMessageSource extends ResourceBundleMessageSource {
@Override
protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException {
protected ResourceBundle doGetBundle(String basename, Locale locale) {
return ResourceBundle.getBundle(basename, locale, YamlResourceBundle.Control.INSTANCE);
}
}

View File

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

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}
}

View File

@@ -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/**");
}
}

View File

@@ -9,23 +9,25 @@ import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
private static final String HELLO = "helloworld";
@Setter
@Getter
public static class Hello {
private static class Hello {
private String message;
}
@GetMapping(value = "/helloworld/string")
@ResponseBody
public String helloworldString() {
return "helloworld";
return HELLO;
}
@GetMapping(value = "/helloworld/json")
@ResponseBody
public Hello helloworldJson() {
Hello hello = new Hello();
hello.message = "helloworld";
hello.message = HELLO;
return hello;
}

View File

@@ -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("");
}
}

View 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();
}
}

View File

@@ -7,13 +7,13 @@ import com.rest.api.model.response.ListResult;
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 io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
@Api(tags = {"1. User"})
@Api(tags = {"2. User"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/v1")
@@ -22,6 +22,9 @@ public class UserController {
private final UserJpaRepo userJpaRepo;
private final ResponseService responseService; // 결과를 처리할 Service
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "회원 리스트 조회", notes = "모든 회원을 조회한다")
@GetMapping(value = "/users")
public ListResult<User> findAllUser() {
@@ -29,40 +32,38 @@ public class UserController {
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,
@ApiParam(value = "언어", defaultValue = "ko") @RequestParam String lang) {
// 결과데이터가 단일건인경우 getBasicResult를 이용해서 결과를 출력한다.
return responseService.getSingleResult(userJpaRepo.findById(msrl).orElseThrow(CUserNotFoundException::new));
}
@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));
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "회원 단건 조회", notes = "회원번호(msrl)로 회원을 조회한다")
@GetMapping(value = "/user")
public SingleResult<User> findUser() {
// SecurityContext에서 인증받은 회원의 정보를 얻어온다.
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String id = authentication.getName();
// 결과데이터가 단일건인경우 getSingleResult를 이용해서 결과를 출력한다.
return responseService.getSingleResult(userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new));
}
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@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로 회원정보를 삭제한다")
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "회원 삭제", notes = "회원번호(msrl)로 회원정보를 삭제한다")
@DeleteMapping(value = "/user/{msrl}")
public CommonResult delete(
@ApiParam(value = "회원번호", required = true) @PathVariable long msrl) {

View File

@@ -1,8 +1,19 @@
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 java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@Builder // builder를 사용할수 있게 합니다.
@Entity // jpa entity임을 알립니다.
@@ -10,13 +21,54 @@ import javax.persistence.*;
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
public class User {
@Id // primaryKey임을 알립니다.
public class User implements UserDetails {
@Id // pk
@GeneratedValue(strategy = GenerationType.IDENTITY)
// pk생성전략을 DB에 위임한다는 의미입니다. mysql로 보면 pk 필드를 auto_increment로 설정해 놓은 경우로 보면 됩니다.
private long msrl;
@Column(nullable = false, unique = true, length = 30) // uid column을 명시합니다. 필수이고 유니크한 필드이며 길이는 30입니다.
@Column(nullable = false, unique = true, length = 50)
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;
@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;
}
}

View File

@@ -2,6 +2,9 @@ package com.rest.api.repo;
import com.rest.api.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserJpaRepo extends JpaRepository<User, Long> {
Optional<User> findByUid(String email);
}

View File

@@ -12,7 +12,7 @@ public class ResponseService {
// enum으로 api 요청 결과에 대한 code, message를 정의합니다.
public enum CommonResponse {
SUCCESS(0, "성공하였습니.");
SUCCESS(0, "성공하였습니.");
int code;
String msg;

View File

@@ -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);
}
}

View File

@@ -12,4 +12,6 @@ spring:
showSql: true
messages:
basename: i18n/exception
encoding: UTF-8
encoding: UTF-8
jwt:
secret: govlepel@$&

View File

@@ -3,4 +3,13 @@ unKnown:
msg: "An unknown error has occurred."
userNotFound:
code: "-1000"
msg: "This member not exist"
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."

View File

@@ -3,4 +3,13 @@ unKnown:
msg: "알수 없는 오류가 발생하였습니다."
userNotFound:
code: "-1000"
msg: "존재하지 않는 회원입니다."
msg: "존재하지 않는 회원입니다."
emailSigninFailed:
code: "-1001"
msg: "계정이 존재하지 않거나 이메일 또는 비밀번호가 정확하지 않습니다."
entryPointException:
code: "-1002"
msg: "해당 리소스에 접근하기 위한 권한이 없습니다."
accessDenied:
code: "-1003"
msg: "보유한 권한으로 접근할수 없는 리소스 입니다."

View File

@@ -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() {
}
}

View File

@@ -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"));
}
}

View File

@@ -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));
}
}

View 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));
}
}

View 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변수 값이 같은지 체크
}
}