1 Commits

Author SHA1 Message Date
kimyonghwa
7cd4d602f7 bugfix
- update ftl path
- delete duplicate security settings
2019-11-14 11:36:35 +09:00
8 changed files with 30 additions and 46 deletions

View File

@@ -1,6 +1,5 @@
package com.rest.api.config.security;
import com.rest.api.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
@@ -9,12 +8,15 @@ 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.*;
import java.util.Base64;
import java.util.Date;
import java.util.List;
@RequiredArgsConstructor
@Component
@@ -23,7 +25,7 @@ public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
@Value("${spring.jwt.secret}")
private String secretKey;
private long tokenValidMilisecond = 1000L * 60 * 60 * 24; // 24시간만 토큰 유효
private long tokenValidMilisecond = 1000L * 60 * 60; // 1시간만 토큰 유효
private final UserDetailsService userDetailsService;
@@ -47,18 +49,13 @@ public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
// Jwt 토큰으로 인증 정보를 조회
public Authentication getAuthentication(String token) {
Map<String, Object> parseInfo = getUserParseInfo(token);
User user = User.builder().uid(String.valueOf(parseInfo.get("msrl"))).roles((List)parseInfo.get("authorities")).build();
return new UsernamePasswordAuthenticationToken(user, "", user.getAuthorities());
UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUserPk(token));
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}
// Jwt 토큰에서 회원 구별 정보 추출
public Map<String, Object> getUserParseInfo(String token) {
Jws<Claims> parseInfo = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
Map<String, Object> result = new HashMap<>();
result.put("msrl", parseInfo.getBody().getSubject());
result.put("authorities", parseInfo.getBody().get("roles", List.class));
return result;
public String getUserPk(String token) {
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
}
// Request의 Header에서 token 파싱 : "X-AUTH-TOKEN: jwt토큰"

View File

@@ -15,7 +15,7 @@ public class HelloController {
@Setter
@Getter
private static class Hello {
public static class Hello {
private String message;
}

View File

@@ -40,8 +40,9 @@ public class UserController {
public SingleResult<User> findUser() {
// SecurityContext에서 인증받은 회원의 정보를 얻어온다.
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String id = authentication.getName();
// 결과데이터가 단일건인경우 getSingleResult를 이용해서 결과를 출력한다.
return responseService.getSingleResult(userJpaRepo.findById(Long.valueOf(authentication.getName())).orElseThrow(CUserNotFoundException::new));
return responseService.getSingleResult(userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new));
}
@ApiImplicitParams({
@@ -53,7 +54,8 @@ public class UserController {
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = userJpaRepo.findById(Long.valueOf(authentication.getName())).orElseThrow(CUserNotFoundException::new);
String id = authentication.getName();
User user = userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new);
user.setName(name);
return responseService.getSingleResult(userJpaRepo.save(user));
}

View File

@@ -28,15 +28,6 @@ public class BoardController {
private final BoardService boardService;
private final ResponseService responseService;
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "게시판 생성", notes = "신규 게시판을 생성한다.")
@PostMapping(value = "/{boardName}")
public SingleResult<Board> createBoard(@PathVariable String boardName) {
return responseService.getSingleResult(boardService.insertBoard(boardName));
}
@ApiOperation(value = "게시판 정보 조회", notes = "게시판 정보를 조회한다.")
@GetMapping(value = "/{boardName}")
public SingleResult<Board> boardInfo(@PathVariable String boardName) {
@@ -53,10 +44,11 @@ public class BoardController {
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "게시글 작성", notes = "게시글을 작성한다.")
@PostMapping(value = "/{boardName}/post")
@PostMapping(value = "/{boardName}")
public SingleResult<Post> post(@PathVariable String boardName, @Valid @ModelAttribute ParamsPost post) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return responseService.getSingleResult(boardService.writePost(Long.valueOf(authentication.getName()), boardName, post));
String uid = authentication.getName();
return responseService.getSingleResult(boardService.writePost(uid, boardName, post));
}
@ApiOperation(value = "게시글 상세", notes = "게시글 상세정보를 조회한다.")
@@ -72,7 +64,8 @@ public class BoardController {
@PutMapping(value = "/post/{postId}")
public SingleResult<Post> post(@PathVariable long postId, @Valid @ModelAttribute ParamsPost post) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return responseService.getSingleResult(boardService.updatePost(postId, Long.valueOf(authentication.getName()), post));
String uid = authentication.getName();
return responseService.getSingleResult(boardService.updatePost(postId, uid, post));
}
@ApiImplicitParams({
@@ -82,7 +75,8 @@ public class BoardController {
@DeleteMapping(value = "/post/{postId}")
public CommonResult deletePost(@PathVariable long postId) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
boardService.deletePost(postId, Long.valueOf(authentication.getName()));
String uid = authentication.getName();
boardService.deletePost(postId, uid);
return responseService.getSuccessResult();
}
}

View File

@@ -1,19 +1,15 @@
package com.rest.api.entity.board;
import com.rest.api.entity.common.CommonDateEntity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
@Builder
@Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Board extends CommonDateEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@@ -7,13 +7,12 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.time.LocalDateTime;
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class CommonDateEntity implements Serializable {
public abstract class CommonDateEntity {
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate

View File

@@ -7,5 +7,5 @@ import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface PostJpaRepo extends JpaRepository<Post, Long> {
List<Post> findByBoardOrderByPostIdDesc(Board board);
List<Post> findByBoard(Board board);
}

View File

@@ -34,10 +34,6 @@ public class BoardService {
private final UserJpaRepo userJpaRepo;
private final CacheSevice cacheSevice;
public Board insertBoard(String boardName) {
return boardJpaRepo.save(Board.builder().name(boardName).build());
}
// 게시판 이름으로 게시판을 조회. 없을경우 CResourceNotExistException 처리
@Cacheable(value = CacheKey.BOARD, key = "#boardName", unless = "#result == null")
public Board findBoard(String boardName) {
@@ -47,7 +43,7 @@ public class BoardService {
// 게시판 이름으로 게시글 리스트 조회.
@Cacheable(value = CacheKey.POSTS, key = "#boardName", unless = "#result == null")
public List<Post> findPosts(String boardName) {
return postJpaRepo.findByBoardOrderByPostIdDesc(findBoard(boardName));
return postJpaRepo.findByBoard(findBoard(boardName));
}
// 게시글ID로 게시글 단건 조회. 없을경우 CResourceNotExistException 처리
@@ -58,18 +54,18 @@ public class BoardService {
// 게시글을 등록합니다. 게시글의 회원UID가 조회되지 않으면 CUserNotFoundException 처리합니다.
@CacheEvict(value = CacheKey.POSTS, key = "#boardName")
public Post writePost(Long msrl, String boardName, ParamsPost paramsPost) {
public Post writePost(String uid, String boardName, ParamsPost paramsPost) {
Board board = findBoard(boardName);
Post post = new Post(userJpaRepo.findById(msrl).orElseThrow(CUserNotFoundException::new), board, paramsPost.getAuthor(), paramsPost.getTitle(), paramsPost.getContent());
Post post = new Post(userJpaRepo.findByUid(uid).orElseThrow(CUserNotFoundException::new), board, paramsPost.getAuthor(), paramsPost.getTitle(), paramsPost.getContent());
return postJpaRepo.save(post);
}
// 게시글을 수정합니다. 게시글 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
//@CachePut(value = CacheKey.POST, key = "#postId") 갱신된 정보만 캐시할경우에만 사용!
public Post updatePost(long postId, Long msrl, ParamsPost paramsPost) {
public Post updatePost(long postId, String uid, ParamsPost paramsPost) {
Post post = getPost(postId);
User user = post.getUser();
if (!msrl.equals(user.getMsrl()))
if (!uid.equals(user.getUid()))
throw new CNotOwnerException();
// 영속성 컨텍스트의 변경감지(dirty checking) 기능에 의해 조회한 Post내용을 변경만 해도 Update쿼리가 실행됩니다.
@@ -79,10 +75,10 @@ public class BoardService {
}
// 게시글을 삭제합니다. 게시글 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
public boolean deletePost(long postId, Long msrl) {
public boolean deletePost(long postId, String uid) {
Post post = getPost(postId);
User user = post.getUser();
if (!msrl.equals(user.getMsrl()))
if (!uid.equals(user.getUid()))
throw new CNotOwnerException();
postJpaRepo.delete(post);
cacheSevice.deleteBoardCache(post.getPostId(), post.getBoard().getName());