From 83a33732e601d79e6c1286e5dd347dcdf30e0dc7 Mon Sep 17 00:00:00 2001 From: Anna-Jin Date: Fri, 15 Jul 2022 20:08:50 +0900 Subject: [PATCH] =?UTF-8?q?#30=20[Update]=20jwt=20=EC=97=90=EB=9F=AC?= =?UTF-8?q?=EA=B0=80=20=ED=84=B0=EC=A1=8C=EC=9D=84=20=EB=95=8C,=20?= =?UTF-8?q?=EC=A0=81=EC=A0=88=ED=95=9C=20=EB=AC=B8=EA=B5=AC=20=EB=B0=98?= =?UTF-8?q?=ED=99=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 미해결 --- .../config/security/SecurityConfig.java | 6 +-- .../baechelin/oauth/exception/ErrorCode.java | 9 +++-- .../RestAuthenticationEntryPoint.java | 37 +++++++++++++++---- .../baechelin/oauth/service/AuthService.java | 15 ++++---- .../mpnp/baechelin/oauth/token/AuthToken.java | 23 ++---------- 5 files changed, 49 insertions(+), 41 deletions(-) diff --git a/src/main/java/com/mpnp/baechelin/config/security/SecurityConfig.java b/src/main/java/com/mpnp/baechelin/config/security/SecurityConfig.java index 3dd117c..2d590a2 100644 --- a/src/main/java/com/mpnp/baechelin/config/security/SecurityConfig.java +++ b/src/main/java/com/mpnp/baechelin/config/security/SecurityConfig.java @@ -60,10 +60,10 @@ protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .and() .authorizeRequests() .requestMatchers(CorsUtils::isPreFlightRequest).permitAll() // cors 요청 허용 - .antMatchers("/**").permitAll() - .antMatchers("/review/**", "/store/bookmark/**", "/store/register").hasAnyAuthority(RoleType.USER.getCode()) + .antMatchers("/review", "/api/bookmark", "/store/register", "/user").hasAnyAuthority(RoleType.USER.getCode(), RoleType.ADMIN.getCode()) .antMatchers("/admin/**").hasAnyAuthority(RoleType.ADMIN.getCode()) - .anyRequest().authenticated() + .antMatchers("/**").permitAll() // 그 외 요청은 모두 허용 + .anyRequest().authenticated() // 위의 요청 외의 요청은 무조건 권한검사 .and() .oauth2Login() // auth2 로그인 활성화 .authorizationEndpoint() diff --git a/src/main/java/com/mpnp/baechelin/oauth/exception/ErrorCode.java b/src/main/java/com/mpnp/baechelin/oauth/exception/ErrorCode.java index 1c636dc..499010c 100644 --- a/src/main/java/com/mpnp/baechelin/oauth/exception/ErrorCode.java +++ b/src/main/java/com/mpnp/baechelin/oauth/exception/ErrorCode.java @@ -10,9 +10,12 @@ public enum ErrorCode { SUCCESS_MESSAGE(200, "SUCCESS"), NOT_FOUND_MESSAGE(500, "NOT FOUND"), FAILED_MESSAGE(500, "서버에서 오류가 발생하였습니다."), - INVALID_ACCESS_TOKEN(400, "Invalid access token."), - INVALID_REFRESH_TOKEN(400, "Invalid refresh token."), - NOT_EXPIRED_TOKEN_YET(400,"Not expired token yet."), + INVALID_ACCESS_TOKEN(401, "유효하지 않은 Access Token입니다."), + INVALID_REFRESH_TOKEN(401, "유효하지 않은 Refresh Token입니다."), + NOT_EXPIRED_TOKEN_YET(401,"만료되지 않은 JWT 토큰입니다."), + EXPIRED_TOKEN(401, "만료된 JWT 토큰입니다."), + WRONG_TYPE_TOKEN(401, "잘못된 JWT 토큰입니다."), + ACCESS_DENIED(401, "접근이 거부되었습니다."), ALREADY_LOGIN_ACCOUNT(400, "ALREADY_LOGIN_ACCOUNT"); private final int code; diff --git a/src/main/java/com/mpnp/baechelin/oauth/exception/RestAuthenticationEntryPoint.java b/src/main/java/com/mpnp/baechelin/oauth/exception/RestAuthenticationEntryPoint.java index dbbbcfd..5814fd5 100644 --- a/src/main/java/com/mpnp/baechelin/oauth/exception/RestAuthenticationEntryPoint.java +++ b/src/main/java/com/mpnp/baechelin/oauth/exception/RestAuthenticationEntryPoint.java @@ -1,5 +1,6 @@ package com.mpnp.baechelin.oauth.exception; +import com.google.gson.JsonObject; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; @@ -18,12 +19,34 @@ public void commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException authException - ) throws IOException, ServletException { - authException.printStackTrace(); - log.info("Responding with unauthorized error. Message = {}", authException.getMessage()); - response.sendError( - HttpServletResponse.SC_UNAUTHORIZED, // 401 에러코드 - authException.getLocalizedMessage() - ); + ) throws IOException { + Integer exception = (Integer)request.getAttribute("exception"); + + if(exception == null) { + setResponse(response, ErrorCode.FAILED_MESSAGE); + } + //잘못된 타입의 토큰인 경우 + else if(exception.equals(ErrorCode.WRONG_TYPE_TOKEN.getCode())) { + setResponse(response, ErrorCode.WRONG_TYPE_TOKEN); + } + //토큰 만료된 경우 + else if(exception.equals(ErrorCode.EXPIRED_TOKEN.getCode())) { + setResponse(response, ErrorCode.EXPIRED_TOKEN); + } + else { + setResponse(response, ErrorCode.ACCESS_DENIED); + } + } + + //한글 출력을 위해 getWriter() 사용 + private void setResponse(HttpServletResponse response, ErrorCode errorCode) throws IOException { + response.setContentType("application/json;charset=UTF-8"); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + + JsonObject responseJson = new JsonObject(); + responseJson.addProperty("message", errorCode.getMessage()); + responseJson.addProperty("code", errorCode.getCode()); + + response.getWriter().print(responseJson); } } diff --git a/src/main/java/com/mpnp/baechelin/oauth/service/AuthService.java b/src/main/java/com/mpnp/baechelin/oauth/service/AuthService.java index 890eb9d..eff42ba 100644 --- a/src/main/java/com/mpnp/baechelin/oauth/service/AuthService.java +++ b/src/main/java/com/mpnp/baechelin/oauth/service/AuthService.java @@ -36,15 +36,14 @@ public AuthResponse refreshToken(HttpServletRequest request, HttpServletResponse String accessToken = HeaderUtil.getAccessToken(request); AuthToken authToken = tokenProvider.convertAuthToken(accessToken); - // 유효한 access token 인지 확인 - if (authToken.getTokenClaimsForRefresh() == null) { - return AuthResponse.invalidAccessToken(); - } - - // expired access token 인지 확인 Claims claims = authToken.getExpiredTokenClaims(); - if (claims == null) { - return AuthResponse.notExpiredTokenYet(); + // 유효한 access token 인지, 만료된 token 인지 확인 + if (authToken.getExpiredTokenClaims() == null) { + return AuthResponse.invalidAccessToken(); + } else { + if (claims == null) { + return AuthResponse.notExpiredTokenYet(); + } } String userId = claims.getSubject(); diff --git a/src/main/java/com/mpnp/baechelin/oauth/token/AuthToken.java b/src/main/java/com/mpnp/baechelin/oauth/token/AuthToken.java index 3e64fb8..d38af84 100644 --- a/src/main/java/com/mpnp/baechelin/oauth/token/AuthToken.java +++ b/src/main/java/com/mpnp/baechelin/oauth/token/AuthToken.java @@ -74,16 +74,15 @@ public Claims getTokenClaims() { return null; } - // Access token을 재발급 받을 때 token이 유효한지 검사하는 로직 - // 만료된 토큰일 때는 통과 - public Claims getTokenClaimsForRefresh() { + // 만료된 토큰인지 확인하는 용도 + public Claims getExpiredTokenClaims() { try { return Jwts.parserBuilder() .setSigningKey(key) .build() .parseClaimsJws(token) .getBody(); - } catch (SecurityException e) { + } catch (SignatureException e) { log.info("잘못된 JWT 서명입니다."); } catch (MalformedJwtException e) { log.info("유효하지 않은 구성의 JWT 토큰입니다."); @@ -97,20 +96,4 @@ public Claims getTokenClaimsForRefresh() { } return null; } - - - // 만료된 토큰인지 확인하는 용도 - public Claims getExpiredTokenClaims() { - try { - Jwts.parserBuilder() - .setSigningKey(key) - .build() - .parseClaimsJws(token) - .getBody(); - } catch (ExpiredJwtException e) { - log.info("만료된 JWT 토큰입니다."); - return e.getClaims(); - } - return null; - } }