-
카테고리
-
해결 여부
미해결
구글 로그인이 정말 몇일째 작동하지 않습니다 ㅠㅠ...
23.11.13 03:10 작성 조회수 222
0
@Service
public class CustomOAuth2LoginSuccessHandler implements AuthenticationSuccessHandler {
private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
@Autowired
private CustomOAuth2UserService customOAuth2UserService;
@Autowired
private OAuth2AuthorizedClientService authorizedClientService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
logger.info("Authentication Success - Principal: {}", authentication.getPrincipal());
OAuth2AuthenticationToken authToken = (OAuth2AuthenticationToken) authentication;
OAuth2User oAuth2User = authToken.getPrincipal();
OAuth2AuthorizedClient authorizedClient = authorizedClientService
.loadAuthorizedClient(authToken.getAuthorizedClientRegistrationId(), authToken.getName());
if (authorizedClient != null) {
OAuth2UserRequest userRequest = new OAuth2UserRequest(authorizedClient.getClientRegistration(), authorizedClient.getAccessToken());
customOAuth2UserService.processOAuth2User(oAuth2User, userRequest);
}
// 인증 후 리디렉션 또는 추가 로직 구현
response.sendRedirect("/home"); // 예시로 '/home'으로 리디렉션
}
}
@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
private static final Logger logger = LoggerFactory.getLogger(CustomOAuth2UserService.class);
@Autowired
private MembersRepository membersRepository;
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
logger.info("loadUser1");
try {
OAuth2UserService<OAuth2UserRequest, OAuth2User> delegate = new DefaultOAuth2UserService();
OAuth2User oAuth2User = delegate.loadUser(userRequest);
logOAuth2UserInfo(oAuth2User); // 로그 출력
processOAuth2User(oAuth2User, userRequest);
return oAuth2User;
} catch (Exception e) {
logger.error("Error loading OAuth2User", e);
throw e;
}
}
private void logOAuth2UserInfo(OAuth2User oAuth2User) {
logger.info("OAuth2User Attributes: {}", oAuth2User.getAttributes());
if (oAuth2User.getAttribute("email") == null) {
logger.warn("OAuth2User does not contain email attribute");
}
}
@Transactional
public void processOAuth2User(OAuth2User oAuth2User, OAuth2UserRequest userRequest) {
String email = oAuth2User.getAttribute("email");
String name = oAuth2User.getAttribute("name");
logger.info("Processing user - Email: {}, Name: {}", email, name);
Optional<MembersEntity> existingMember = membersRepository.findByEmail(email);
MembersEntity member;
if (existingMember.isPresent()) {
member = existingMember.get();
member.updateFromGoogle(name, email);
logger.info("Updated existing user: {}", email);
} else {
member = MembersEntity.builder()
.email(email)
.name(name)
.nickname(name + "_google")
.role(Role.ROLE_CUSTOMER)
.build();
logger.info("Saving new user: {}", email);
}
try {
membersRepository.save(member);
logger.info("User saved/updated successfully: {}", email);
} catch (Exception e) {
logger.error("Error saving/updating user: {}", email, e);
}
membersRepository.save(member);
}
}
@RestController
public class LoginController {
private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
@GetMapping("/login/oauth2")
public void redirectToLoginPage(HttpServletResponse response) throws IOException {
// OAuth2 로그인 페이지로 리디렉션
logger.info("리다이렉트");
response.sendRedirect("/oauth2/authorization/google");
}
}
답변을 작성해보세요.
0
김태현
질문자2023.11.13
해당 코드를 돌릴때 나오는 로그는 다음과 같습니다.
... 초반생략
2023-11-13T03:06:14.069+09:00 DEBUG 10264 --- [nio-9876-exec-1] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2023-11-13T03:06:14.069+09:00 INFO 10264 --- [nio-9876-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 3 ms
2023-11-13T03:06:14.079+09:00 DEBUG 10264 --- [nio-9876-exec-1] o.s.security.web.FilterChainProxy : Securing GET /login/oauth2
2023-11-13T03:06:14.090+09:00 DEBUG 10264 --- [nio-9876-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2023-11-13T03:06:14.090+09:00 DEBUG 10264 --- [nio-9876-exec-1] o.s.s.w.session.SessionManagementFilter : Request requested invalid session id 66AA15520FCB4EAE12BD3B03610D2968
2023-11-13T03:06:14.092+09:00 DEBUG 10264 --- [nio-9876-exec-1] o.s.security.web.FilterChainProxy : Secured GET /login/oauth2
2023-11-13T03:06:14.095+09:00 DEBUG 10264 --- [nio-9876-exec-1] o.s.web.servlet.DispatcherServlet : GET "/login/oauth2", parameters={}
2023-11-13T03:06:14.109+09:00 DEBUG 10264 --- [nio-9876-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.aucison_service.controller.LoginController#redirectToLoginPage(HttpServletResponse)
2023-11-13T03:06:14.131+09:00 INFO 10264 --- [nio-9876-exec-1] c.e.a.controller.AuthController : 리다이렉트
2023-11-13T03:06:14.133+09:00 DEBUG 10264 --- [nio-9876-exec-1] o.s.web.servlet.DispatcherServlet : Completed 302 FOUND
2023-11-13T03:06:14.140+09:00 DEBUG 10264 --- [nio-9876-exec-2] o.s.security.web.FilterChainProxy : Securing GET /oauth2/authorization/google
2023-11-13T03:06:14.471+09:00 WARN 10264 --- [nio-9876-exec-2] o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [305] milliseconds.
2023-11-13T03:06:14.477+09:00 DEBUG 10264 --- [nio-9876-exec-2] o.s.s.web.DefaultRedirectStrategy : Redirecting to https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=76213274445-a48jff50a3frvb7s1urp6eog1ukdckj2.apps.googleusercontent.com&scope=openid%20profile%20email&state=3NycGBPL1xadvv5bopFVPzDl_6BemdFJY9IBGoLtZfQ%3D&redirect_uri=http://localhost:9876/api/auth/google/callback&nonce=f8T6sOTy4-9JlCZUj_RP-NG-PVfJi6sitl9Z5-7RapI
2023-11-13T03:06:14.789+09:00 DEBUG 10264 --- [nio-9876-exec-3] o.s.security.web.FilterChainProxy : Securing GET /api/auth/google/callback?state=3NycGBPL1xadvv5bopFVPzDl_6BemdFJY9IBGoLtZfQ%3D&code=4%2F0AfJohXlk24UlWLZ0MM_kgx9O5QxdyvkzP2P1nQgIvSa8FmuSsctmRClKl-WBNZHPLSsTOA&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=none
2023-11-13T03:06:14.790+09:00 DEBUG 10264 --- [nio-9876-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2023-11-13T03:06:14.790+09:00 DEBUG 10264 --- [nio-9876-exec-3] o.s.security.web.FilterChainProxy : Secured GET /api/auth/google/callback?state=3NycGBPL1xadvv5bopFVPzDl_6BemdFJY9IBGoLtZfQ%3D&code=4%2F0AfJohXlk24UlWLZ0MM_kgx9O5QxdyvkzP2P1nQgIvSa8FmuSsctmRClKl-WBNZHPLSsTOA&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=none
2023-11-13T03:06:14.791+09:00 DEBUG 10264 --- [nio-9876-exec-3] o.s.web.servlet.DispatcherServlet : GET "/api/auth/google/callback?state=3NycGBPL1xadvv5bopFVPzDl_6BemdFJY9IBGoLtZfQ%3D&code=4%2F0AfJohXlk24UlWLZ0MM_kgx9O5QxdyvkzP2P1nQgIvSa8FmuSsctmRClKl-WBNZHPLSsTOA&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=none", parameters={masked}
2023-11-13T03:06:14.792+09:00 DEBUG 10264 --- [nio-9876-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.aucison_service.controller.AuthController#handleGoogleCallback(OAuth2User)
2023-11-13T03:06:14.795+09:00 WARN 10264 --- [nio-9876-exec-3] c.e.a.controller.AuthController : Authentication failed - principal is null
2023-11-13T03:06:14.822+09:00 DEBUG 10264 --- [nio-9876-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Using 'text/html', given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, /;q=0.8, application/signed-exchange;v=b3;q=0.7] and supported [text/plain, /, application/json, application/*+json, application/cbor]
2023-11-13T03:06:14.823+09:00 DEBUG 10264 --- [nio-9876-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Writing ["로그인 실패"]
2023-11-13T03:06:14.830+09:00 DEBUG 10264 --- [nio-9876-exec-3] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2023-11-13T03:06:14.893+09:00 DEBUG 10264 --- [nio-9876-exec-4] o.s.security.web.FilterChainProxy : Securing GET /favicon.ico
작업환경은 java17, maven4.0, 스프링부트3.1.4 버전입니다.
테스트 진행 방식은 https 혹은 http 방식으로 로컬 혹은 이미 배포된 도메인의 /login/oauth2로 접속하여 로그인페이지로 리다이렉트로 이동하는 방식입니다.
로그인시 화면에 "로그인 실패" 문자열과 위의 로그가 나오게 됩니다.
정말 간절합니다. 몇일째 해결을 못해서 해탈할 것 같습니다.
답변 1