Skip to content

Commit

Permalink
Merge pull request #58 from BOOK-TALK/#54-edit-api-format
Browse files Browse the repository at this point in the history
#54 edit api format 2
  • Loading branch information
chanwoo7 authored Aug 17, 2024
2 parents e57813e + f848cf1 commit 8048170
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,37 +44,40 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
String authorization = wrappedRequest.getHeader("Authorization");
String username = "", token = "";

if (authorization != null && authorization.startsWith("Bearer ")) { // Bearer 토큰 파싱
token = authorization.substring(7); // jwt token 파싱
try {
try {
if (authorization != null && authorization.startsWith("Bearer ")) { // Bearer 토큰 파싱
token = authorization.substring(7); // jwt token 파싱
username = jwtUtil.getUsernameFromToken(token); // username 가져옴
} catch (ExpiredJwtException e) {
filterChain.doFilter(wrappedRequest, response);
return;
}

// 현재 SecurityContextHolder에 인증객체가 있는지 확인
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails;
try {
userDetails = userDetailsService.loadUserByUsername(username);
} catch (CustomException e) {
userDetails = userDetailsService.loadUserByKakaoId(username);
}
// 현재 SecurityContextHolder에 인증객체가 있는지 확인
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails;
try {
userDetails = userDetailsService.loadUserByUsername(username);
} catch (CustomException e) {
userDetails = userDetailsService.loadUserByKakaoId(username);
}

// 토큰 유효성 검증
if (jwtUtil.isValidToken(token, userDetails)) {
UsernamePasswordAuthenticationToken authenticated
= new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
// 토큰 유효성 검증
if (jwtUtil.isValidToken(token, userDetails)) {
UsernamePasswordAuthenticationToken authenticated
= new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

authenticated.setDetails(new WebAuthenticationDetailsSource().buildDetails(wrappedRequest));
SecurityContextHolder.getContext().setAuthentication(authenticated);
authenticated.setDetails(new WebAuthenticationDetailsSource().buildDetails(wrappedRequest));
SecurityContextHolder.getContext().setAuthentication(authenticated);

// 토큰 갱신
String newAccessToken = jwtUtil.generateToken(userDetails).getAccessToken();
response.setHeader("Authorization", "Bearer " + newAccessToken);
// 토큰 갱신
String newAccessToken = jwtUtil.generateToken(userDetails).getAccessToken();
response.setHeader("Authorization", "Bearer " + newAccessToken);
}
}
} else {
request.setAttribute("JWTException", new CustomException(ErrorCode.JWT_NOT_FOUND));
}
} catch (ExpiredJwtException e) {
request.setAttribute("JWTException", new CustomException(ErrorCode.JWT_EXPIRED));
} catch (Exception e) {
request.setAttribute("JWTException", new CustomException(ErrorCode.INVALID_CREDENTIALS));
}

filterChain.doFilter(wrappedRequest, response);
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/book/backend/exception/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ public enum ErrorCode {

INVALID_CREDENTIALS(HttpStatus.UNAUTHORIZED, "401", "사용자 인증에 실패했습니다."),
LOGIN_REQUIRED(HttpStatus.UNAUTHORIZED, "401", "로그인이 필요합니다."),
JWT_EXPIRED(HttpStatus.UNAUTHORIZED, "401", "JWT 토큰이 만료되었습니다. 다시 로그인해주세요."),
JWT_NOT_FOUND(HttpStatus.UNAUTHORIZED, "401", "JWT 토큰이 입력되지 않았습니다."),
JWT_EXPIRED(HttpStatus.UNAUTHORIZED, "401", "JWT 토큰이 만료되었습니다."),
USER_NOT_FOUND(HttpStatus.NOT_FOUND, "404", "해당하는 사용자를 찾을 수 없습니다."),
LOGIN_ID_DUPLICATED(HttpStatus.CONFLICT,"409", "사용자의 아이디가 중복됩니다."),
BAD_REQUEST(HttpStatus.BAD_REQUEST, "400", "요청이 잘못되었습니다."),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.book.backend.global;

import com.book.backend.exception.CustomException;
import com.book.backend.exception.ErrorCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
Expand All @@ -13,13 +12,14 @@
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
CustomException customException = new CustomException(ErrorCode.LOGIN_REQUIRED);
CustomException customException = (CustomException) request.getAttribute("JWTException");
response.setStatus(customException.getCode().getStatus().value());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(
"{\"statusCode\": \"" + customException.getCode().getCode() + "\", " +
"{\"statusCode\": " + customException.getCode().getCode() + ", " +
"\"message\": \"" + customException.getCode().getMessage() + "\"}");

response.getWriter().flush();
}
}

0 comments on commit 8048170

Please sign in to comment.