Compare commits
2 Commits
master
...
feature/fi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d69cc6b147 | ||
|
|
1b367a501f |
@@ -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
|
||||
@@ -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토큰"
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -56,8 +56,7 @@ public class BoardController {
|
||||
@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 = "게시글 상세정보를 조회한다.")
|
||||
@@ -73,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({
|
||||
@@ -84,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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,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쿼리가 실행됩니다.
|
||||
@@ -79,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());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
logging:
|
||||
level:
|
||||
root: debug
|
||||
root: info
|
||||
com.rest.api: debug
|
||||
|
||||
spring:
|
||||
|
||||
Reference in New Issue
Block a user