Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,22 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import tp.farming_springboot.application.dto.response.TokenDto;
import tp.farming_springboot.application.dto.request.UserAuthenDto;
import tp.farming_springboot.application.dto.request.UserCreateDto;
import tp.farming_springboot.application.AuthenticateService;
import tp.farming_springboot.application.OtpService;
import tp.farming_springboot.domain.entity.User;
import tp.farming_springboot.domain.repository.UserRepository;
import tp.farming_springboot.infra.SmsService;
import tp.farming_springboot.application.UserService;
import tp.farming_springboot.domain.exception.UserExistsException;
import tp.farming_springboot.domain.exception.VerificationException;

import java.nio.charset.Charset;
import java.util.Optional;

@CrossOrigin
@RestController
Expand All @@ -30,6 +34,7 @@ public class AuthenticateController {
private final SmsService smsService;
private final AuthenticateService authenticateService;
private final UserService userService;
private final UserRepository userRepository;

public HttpHeaders HttpHeaderSetting(){
HttpHeaders headers = new HttpHeaders();
Expand All @@ -46,6 +51,13 @@ public ResponseEntity<?> temp(@RequestBody UserAuthenDto logger){
}

//renew tokens
@GetMapping("/gen-tokens")
public ResponseEntity<?> sendTokens(Authentication authentication){
Optional<User> user = userRepository.findByPhone(authentication.getName());
TokenDto tokenDto = authenticateService.getNewTokens(user.get().getPhone());
ApiResponse message = new ApiResponse(ResultCode.OK,"Generating token success.", tokenDto);
return new ResponseEntity<>(message, HttpHeaderSetting(), HttpStatus.OK);
}
Comment on lines +54 to +60
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

authentication.getName()이 user.get().getPhone()과 같은 데이터인데 불필요한 유저 조회가 한번 더 들어가는 것 같습니다~

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

또, 귀찮겠지만 ResponseEntity는 더이상 사용하지 않고 ApiReponse만 반환하도록 했습니다 ㅎ ProductController 참고하시고

이유는 데이터 -> (감싸기) -> ApiReponse -> (또 감싸기) -> ResponseEntity 이렇게 두번씩 감쌀 필요가 없다는 생각때문입니다


//send otp number to user
@PostMapping("/request-otp")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import tp.farming_springboot.api.ResultCode;

import java.util.HashMap;

@RequiredArgsConstructor
@Component
Expand All @@ -42,12 +42,19 @@ public class AuthTokenFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws IOException {
try {
String jwt = parseJwt(request);
if (jwtUtils.validateJwtToken(jwt)) {
HashMap<String, String> map = parseJwt(request);
if(map.containsKey("access")){
String jwt = map.get("access");
jwtUtils.validateJwtToken(jwt);
String username = jwtUtils.getUserNameFromJwtToken(jwt);
jwtUtils.createAuthentication(username);
}

else if(map.containsKey("refresh")){
String jwt = map.get("refresh");
jwtUtils.validateJwtRefresh(jwt);
String username = jwtUtils.getUserNameFromJwtRefreshToken(jwt);
jwtUtils.createAuthentication(username);
}
filterChain.doFilter(request, response);
Comment on lines 44 to 58
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

로직이 access token 검사 후 혹시 refresh token이 있다면 refresh 토큰으로도 인증이 성공하도록 되어있는데요,

프론트쪽에서 access token과 refresh token을 동시에 사용해야할 일이 있을까요? refresh token은 최대한 사용을 자제하면서 노출을 피하고, access token을 재발급하기 위한 용도로만 사용하는 것이 맞지 않나 싶은데 의견부탁해요~~~

  1. 프론트쪽에서 access token 기반 요청 => 만료
  2. 프론트쪽에서 refresh token으로 access token 재발급 요청
  3. 프론트쪽에서 access token 기반 재요청

}
catch(BadCredentialsException e) {
Expand Down Expand Up @@ -84,14 +91,19 @@ protected boolean shouldNotFilter(HttpServletRequest request) {
return EXCLUDE_URL.stream().anyMatch(exclude -> exclude.equalsIgnoreCase(request.getServletPath()));
}

private String parseJwt(HttpServletRequest request) {
private HashMap<String, String> parseJwt(HttpServletRequest request) {
String headerAuth = request.getHeader("Authorization");

HashMap<String, String> map = new HashMap<>();
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
return headerAuth.substring(7);
} else {
map.put("access",headerAuth.substring(7));
}
else if(StringUtils.hasText(headerAuth) && headerAuth.startsWith("Refresh ")){
map.put("refresh",headerAuth.substring(8));
}
else {
throw new BadCredentialsException("토큰 정보가 헤더에 없습니다.");
}

return map;
}

}