Skip to content

Commit

Permalink
Merge pull request #32 from 9oormthon-univ/dev
Browse files Browse the repository at this point in the history
token fix
  • Loading branch information
sumin220 authored Nov 22, 2024
2 parents 56126f4 + 74dc920 commit 3e065f5
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 81 deletions.
24 changes: 0 additions & 24 deletions src/main/java/univ/yesummit/global/auth/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,18 @@
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.OncePerRequestFilter;
import univ.yesummit.global.auth.util.JwtUtils;
import univ.yesummit.global.oauth.OAuth2MemberService;
Expand Down Expand Up @@ -56,9 +51,6 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
// csrf 차단
.csrf(AbstractHttpConfigurer::disable)

// cors 설정
// .cors(cors -> cors.configurationSource(corsConfigurationSource()))

// 시큐리티 기본 로그인 비활성화
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
Expand Down Expand Up @@ -99,22 +91,6 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.build();
}

// @Value("${cors.allowed-origins")
// private List<String> allowOriginList;

// @Bean
// public CorsConfigurationSource corsConfigurationSource() {
// CorsConfiguration configuration = new CorsConfiguration();
// configuration.addAllowedOrigin("http://localhost:3000"); // 클라이언트 주소
// configuration.addAllowedMethod("*");
// configuration.addAllowedHeader("*");
// configuration.setAllowCredentials(true);
// configuration.addExposedHeader("Authorization");
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// source.registerCorsConfiguration("/**", configuration);
// return source;
// }

public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtUtils jwtUtils;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,6 @@ public class WebMvcConfig implements WebMvcConfigurer {

private final AuthArgumentResolver authArgumentResolver;

// @Override
// public void addCorsMappings(final CorsRegistry registry ){
// registry.addMapping("/**")
// .allowedOriginPatterns("*")
// .allowedMethods("PATCH","GET","POST","PUT","DELETE","HEAD","OPTIONS")
// .allowedHeaders("*")
// .allowCredentials(true);
// }

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
WebMvcConfigurer.super.addArgumentResolvers(resolvers); // 기존 Resolver
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
package univ.yesummit.global.auth.controller;

import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;


import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/v1/api/kakao")
public class AuthController {
Expand All @@ -22,18 +15,4 @@ public class AuthController {
public RedirectView login() {
return new RedirectView("/oauth2/authorization/kakao");
}

@GetMapping("/status")
@Operation(summary = "로그인 상태 확인", description = "사용자의 로그인 상태를 확인합니다.")
public ResponseEntity<Map<String, Boolean>> getLoginStatus(HttpServletRequest request) {
// 쿠키 또는 세션에서 로그인 상태를 확인
HttpSession session = request.getSession(false); // 세션이 없으면 null 반환
boolean loggedIn = session != null && session.getAttribute("user") != null;

// 응답 데이터 생성
Map<String, Boolean> response = new HashMap<>();
response.put("loggedIn", loggedIn);

return ResponseEntity.ok(response);
}
}
}
38 changes: 12 additions & 26 deletions src/main/java/univ/yesummit/global/oauth/OAuth2SuccessHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,34 +44,20 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
throw new RuntimeException(e);
}

// 토큰을 HttpOnly 쿠키에 저장
int accessTokenMaxAge = jwtUtils.getAccessExpiration().intValue() / 1000; // 초 단위로 변환
int refreshTokenMaxAge = jwtUtils.getRefreshExpiration().intValue() / 1000;
// 첫 로그인 여부 확인
boolean isFirstLogin = memberService.isFirstLogin(memberId);

ResponseCookie accessTokenCookie = ResponseCookie.from("accessToken", accessToken)
.httpOnly(true)
.secure(true) // HTTPS에서만 동작
.sameSite("None")
.path("/")
.maxAge(accessTokenMaxAge)
.build();
// JSON 응답으로 전달할 데이터 생성
Map<String, Object> responseData = new HashMap<>();
responseData.put("accessToken", accessToken);
responseData.put("refreshToken", refreshToken);
responseData.put("firstLogin", isFirstLogin);

ResponseCookie refreshTokenCookie = ResponseCookie.from("refreshToken", refreshToken)
.httpOnly(true)
.secure(true)
.sameSite("None")
.path("/")
.maxAge(refreshTokenMaxAge)
.build();
// JSON 응답 설정
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");

response.addHeader("Set-Cookie", accessTokenCookie.toString());
response.addHeader("Set-Cookie", refreshTokenCookie.toString());

// 첫 로그인 여부에 따라 리다이렉트
if (memberService.isFirstLogin(memberId)) {
response.sendRedirect("http://localhost:3000/signup");
} else {
response.sendRedirect("http://localhost:3000/home");
}
// JSON 데이터를 응답으로 전송
new ObjectMapper().writeValue(response.getWriter(), responseData);
}
}

0 comments on commit 3e065f5

Please sign in to comment.