Skip to content

Commit

Permalink
#30 [Update] jwt 에러가 터졌을 때, 적절한 문구 반환
Browse files Browse the repository at this point in the history
미해결
  • Loading branch information
Anna-Jin committed Jul 15, 2022
1 parent 1abde06 commit 83a3373
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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);
}
}
15 changes: 7 additions & 8 deletions src/main/java/com/mpnp/baechelin/oauth/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
23 changes: 3 additions & 20 deletions src/main/java/com/mpnp/baechelin/oauth/token/AuthToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 토큰입니다.");
Expand All @@ -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;
}
}

0 comments on commit 83a3373

Please sign in to comment.