10 Commits

Author SHA1 Message Date
kimyonghwa
d69cc6b147 bugfix
- update ftl path
- delete duplicate security settings
2019-11-14 11:38:35 +09:00
kimyonghwa
1b367a501f token검증시 회원정보를 조회하지 않고 Authentication정보를 SpringSecurityContext에 세팅하도록 수정 2019-09-26 22:53:41 +09:00
kimyonghwa
2ffb5d307e change settings
- token expire time : 1hour -> 1day
- log level : info -> debug
2019-09-19 12:12:28 +09:00
codej99
820cb20d27 Merge pull request #21 from codej99/feature/board
add api
2019-09-17 17:35:44 +09:00
codej99
37b4b9cd73 Merge branch 'master' into feature/board 2019-09-17 17:35:37 +09:00
kimyonghwa
4173fc1225 add api
- create board
2019-09-17 17:34:13 +09:00
kimyonghwa
200168c601 Merge branch 'feature/board' 2019-09-05 23:14:52 +09:00
kimyonghwa
a51dce74ad post 정렬 추가 2019-09-05 23:13:20 +09:00
kimyonghwa
d4e74d92c1 Serializable 추가 2019-09-04 00:55:07 +09:00
codej99
8cecd7edcf Merge pull request #20 from codej99/cache-data-redis
Cache data redis
2019-08-08 02:09:31 +09:00
9 changed files with 48 additions and 32 deletions

View File

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

View File

@@ -32,7 +32,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.and()
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
.antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
.antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
.antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/**", "/favicon.ico").permitAll() // 등록한 GET요청 리소스는 누구나 접근가능
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
.and()
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())

View File

@@ -15,7 +15,7 @@ public class HelloController {
@Setter
@Getter
public static class Hello {
private static class Hello {
private String message;
}
@@ -37,7 +37,7 @@ public class HelloController {
@GetMapping(value = "/helloworld/page")
public String helloworld() {
return HELLO;
return "helloworld";
}
@GetMapping("/helloworld/long-process")

View File

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

View File

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

View File

@@ -1,15 +1,19 @@
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,12 +7,13 @@ 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 {
public abstract class CommonDateEntity implements Serializable {
@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> findByBoard(Board board);
List<Post> findByBoardOrderByPostIdDesc(Board board);
}

View File

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