-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
41 changes: 41 additions & 0 deletions
41
...ava/site/timecapsulearchive/core/global/security/jwt/JwtAuthenticationFailureHandler.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
package site.timecapsulearchive.core.global.security.jwt; | ||
|
||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import java.io.IOException; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.http.MediaType; | ||
import org.springframework.security.core.AuthenticationException; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.security.web.authentication.AuthenticationFailureHandler; | ||
import org.springframework.stereotype.Component; | ||
import site.timecapsulearchive.core.global.common.response.ErrorCode; | ||
import site.timecapsulearchive.core.global.common.response.ErrorResponse; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler { | ||
|
||
private final ObjectMapper objectMapper; | ||
|
||
@Override | ||
public void onAuthenticationFailure( | ||
HttpServletRequest request, | ||
HttpServletResponse response, | ||
AuthenticationException exception | ||
) throws IOException { | ||
SecurityContextHolder.clearContext(); | ||
|
||
ErrorResponse errorResponse = ErrorResponse.create( | ||
ErrorCode.INVALID_TOKEN_EXCEPTION.getCode(), | ||
exception.getMessage() | ||
); | ||
|
||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); | ||
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); | ||
|
||
response.getWriter() | ||
.write(objectMapper.writeValueAsString(errorResponse)); | ||
} | ||
} |