Skip to content

Commit

Permalink
Fix(#89): 로그아웃 쿠키, redis 삭제
Browse files Browse the repository at this point in the history
  • Loading branch information
somin-jeong committed Jul 29, 2024
1 parent a47ff29 commit fd43ca2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
8 changes: 1 addition & 7 deletions src/main/java/inandout/backend/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.logout(logout -> logout
.logoutUrl("/logout")
// 로그아웃 핸들러 추가 (세션 무효화 처리)
.addLogoutHandler(new LogoutHandler())
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.sendRedirect("https://stuffinout.site/login");
}
})
.addLogoutHandler(new LogoutHandler(redisService))
.deleteCookies("JSESSIONID", "refreshToken"));

return http.build();
Expand Down
21 changes: 21 additions & 0 deletions src/main/java/inandout/backend/jwt/LogoutHandler.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
package inandout.backend.jwt;

import inandout.backend.service.login.RedisService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;

import java.util.Objects;

@Component
@RequiredArgsConstructor
public class LogoutHandler extends SecurityContextLogoutHandler {
private final RedisService redisService;
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
if (this.isInvalidateHttpSession()) {
Expand All @@ -18,8 +28,19 @@ public void logout(HttpServletRequest request, HttpServletResponse response, Aut
}
}

for (Cookie cookie : request.getCookies()) {
String cookieName = cookie.getName();
Cookie cookieToDelete = new Cookie(cookieName, null);
cookieToDelete.setMaxAge(0);
response.addCookie(cookieToDelete);
}

SecurityContext context = SecurityContextHolder.getContext();
SecurityContextHolder.clearContext();
context.setAuthentication(null);

// redis의 refreshToken 삭제
Cookie refreshToken = WebUtils.getCookie(request, "refreshToken");
redisService.deleteRefreshToken(Objects.requireNonNull(refreshToken).getValue());
}
}

0 comments on commit fd43ca2

Please sign in to comment.