Repository navigation
[FEAT] 소셜 로그인 API및 Security, JWT #41
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 13 commits
483f11b
cf73e51
60fb0e8
7c67b37
e1e71c2
346270b
17e5f51
ff23e22
e48ba51
bd65765
7ba95bb
da3a472
0b6a6bd
4926638
a636bb4
6613435
879730a
3bfaaaa
809047b
1ffca71
6119db5
bc04e7c
678eb4e
0ed59e6
76ee530
8120ae7
f19f57c
8c45bc1
5b69e50
65967dc
c0e7b86
f609452
3754aa3
bb295aa
4530b88
d8a49eb
1ab1d2a
1b90a4d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package com.mr.domain.auth.controller; | ||
|
|
||
| import com.mr.domain.auth.dto.AuthRequestDTO; | ||
| import com.mr.domain.auth.dto.AuthResponseDTO; | ||
| import com.mr.domain.auth.entity.enums.SocialType; | ||
| import com.mr.domain.auth.service.AuthService; | ||
| import com.mr.global.apipayload.ApiResponse; | ||
| import jakarta.validation.Valid; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.web.bind.annotation.*; | ||
|
|
||
| @RestController | ||
| @RequiredArgsConstructor | ||
| @RequestMapping("/api/v1/auth") | ||
| public class AuthController { | ||
|
kimyw1018 marked this conversation as resolved.
Resolved
|
||
|
|
||
| private final AuthService authService; | ||
|
|
||
| @PostMapping("/login/{socialType}") | ||
| public ApiResponse<AuthResponseDTO.LoginResponse> socialLogin( | ||
| @PathVariable(name = "socialType") SocialType socialType, | ||
|
kimyw1018 marked this conversation as resolved.
Resolved
|
||
| @RequestBody @Valid AuthRequestDTO.SocialLoginRequest request | ||
| ) { | ||
| AuthResponseDTO.LoginResponse response = authService.socialLogin(socialType, request.accessToken()); | ||
| return ApiResponse.onSuccess(response); | ||
| } | ||
|
kimyw1018 marked this conversation as resolved.
Resolved
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package com.mr.domain.auth.dto; | ||
|
|
||
| import jakarta.validation.constraints.NotBlank; | ||
|
|
||
| public class AuthRequestDTO { | ||
|
|
||
| public record SocialLoginRequest( | ||
| @NotBlank(message = "소셜 액세스 토큰은 필수 입력값입니다.") | ||
| String accessToken | ||
| ) {} | ||
|
|
||
| public record TokenRefreshRequest( | ||
| @NotBlank(message = "Refresh Token은 필수 입력값입니다.") | ||
| String refreshToken | ||
| ) {} | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| package com.mr.domain.auth.dto; | ||
|
|
||
| import lombok.Builder; | ||
|
|
||
| public class AuthResponseDTO { | ||
|
|
||
| @Builder | ||
| public record TokenResponse( | ||
| String accessToken, | ||
| String refreshToken, | ||
| Long tokenExpirationTime | ||
|
kimyw1018 marked this conversation as resolved.
Resolved
|
||
| ) {} | ||
|
|
||
| @Builder | ||
| public record LoginResponse( | ||
| Long userId, | ||
| String email, | ||
| String nickname, | ||
| Boolean isNewUser, // 최초 가입 여부 | ||
|
kimyw1018 marked this conversation as resolved.
Resolved
|
||
| TokenResponse tokenInfo | ||
| ) {} | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| package com.mr.domain.auth.service; | ||
|
|
||
| import com.mr.domain.auth.dto.AuthResponseDTO; | ||
| import com.mr.domain.auth.entity.enums.SocialType; | ||
| import com.mr.global.security.jwt.JwtTokenProvider; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| @Service | ||
| @RequiredArgsConstructor | ||
| @Transactional(readOnly = true) | ||
| public class AuthService { | ||
|
|
||
| private final JwtTokenProvider jwtTokenProvider; | ||
| // private final KakaoOAuthService kakaoOAuthService; (외부 API 파싱용 서비스) | ||
| // private final GoogleOAuthService googleOAuthService; | ||
|
|
||
| @Transactional | ||
| public AuthResponseDTO.LoginResponse socialLogin(SocialType socialType, String accessToken) { | ||
| // 1. 외부 소셜 API (카카오/구글) 통신하여 유저 프로필(email, socialId) 파싱 | ||
| // SocialUserInfo userInfo = getSocialUserInfo(socialType, accessToken); | ||
|
|
||
| // 2. TODO: User 엔티티 연동 및 가입여부 검증 (Stub 구조) | ||
| // 만약 가입 안 되어있으면 DB User 생성 -> 저장 | ||
| Long mockUserId = 1L; | ||
| String mockEmail = "user@example.com"; | ||
| String mockNickname = "뮤즈유저"; | ||
| boolean isNewUser = false; | ||
|
|
||
| String appAccessToken = jwtTokenProvider.createAccessToken(mockUserId); | ||
| String appRefreshToken = jwtTokenProvider.createRefreshToken(mockUserId); | ||
|
Comment on lines
+20
to
+32
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win 🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -euo pipefail
echo "== candidate files =="
git ls-files | rg 'AuthService\.java|CustomUserDetailsService\.java|User\.java|JwtTokenProvider\.java|UserRepository\.java|CustomUserCredentials\.java|spring-security|SecurityConfig\.java' || true
echo
echo "== AuthService excerpt =="
if [ -f src/main/java/com/mr/domain/auth/service/AuthService.java ]; then
nl -ba src/main/java/com/mr/domain/auth/service/AuthService.java | sed -n '1,220p'
fi
echo
echo "== CustomUserDetailsService excerpt =="
if [ -f src/main/java/com/mr/global/security/principal/CustomUserDetailsService.java ]; then
nl -ba src/main/java/com/mr/global/security/principal/CustomUserDetailsService.java | sed -n '1,140p'
fi
echo
echo "==Jwt token provider and user-related references =="
rg -n "createAccessToken|createRefreshToken|loadUserByUsername|findById|isActivate|ROLE|SocialType|socialId|accessToken|jwtTokenProvider" src/main/java -S || trueRepository: Musereview/BE Length of output: 546 🏁 Script executed: #!/bin/bash
set -euo pipefail
echo "== AuthService excerpt =="
sed -n '1,220p' src/main/java/com/mr/domain/auth/service/AuthService.java | cat -n
echo
echo "== CustomUserDetailsService excerpt =="
sed -n '1,140p' src/main/java/com/mr/global/security/principal/CustomUserDetailsService.java | cat -n
echo
echo "== JwtTokenProvider excerpt =="
sed -n '1,220p' src/main/java/com/mr/global/security/jwt/JwtTokenProvider.java | cat -n
echo
echo "== User entity excerpt =="
sed -n '1,220p' src/main/java/com/mr/domain/user/entity/User.java | cat -n
echo
echo "== Search for user/security/token usages =="
rg -n "createAccessToken|createRefreshToken|loadUserByUsername|findById|isActivate|ROLE|SocialType|socialId|accessToken|jwtTokenProvider|SecurityContextHolder|authentication" src/main/java -S || trueRepository: Musereview/BE Length of output: 15775 소셜 토큰 검증과 실제 사용자 조회를 연결하세요.
📍 Affects 2 files
🤖 Prompt for AI Agents
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 다음 pr에서 구현 예정 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
원하시면 후속 작업을 추적할 GitHub 이슈를 생성해 드릴까요? 🐰 |
||
|
|
||
| AuthResponseDTO.TokenResponse tokenResponse = AuthResponseDTO.TokenResponse.builder() | ||
| .accessToken(appAccessToken) | ||
| .refreshToken(appRefreshToken) | ||
| .tokenExpirationTime(3600L) | ||
| .build(); | ||
|
Comment on lines
+35
to
+39
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win 토큰 만료 시간을 JWT 설정과 동일한 소스에서 계산하세요.
🤖 Prompt for AI Agents
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 다음 pr 에서 구현 예정 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
원하시면 이 작업을 추적할 GitHub 이슈를 만들어 드릴까요? 🐇 |
||
|
|
||
| return AuthResponseDTO.LoginResponse.builder() | ||
| .userId(mockUserId) | ||
| .email(mockEmail) | ||
| .nickname(mockNickname) | ||
| .isNewUser(isNewUser) | ||
| .tokenInfo(tokenResponse) | ||
| .build(); | ||
| } | ||
| } | ||
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| package com.mr.global.config; | ||
|
|
||
| public class SwaggerConfig { | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| package com.mr.global.security; | ||
|
|
||
| import com.mr.global.security.jwt.JwtAccessDeniedHandler; | ||
| import com.mr.global.security.jwt.JwtAuthenticationEntryPoint; | ||
| import com.mr.global.security.jwt.JwtAuthenticationFilter; | ||
| import com.mr.global.security.jwt.JwtTokenProvider; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| 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.http.SessionCreationPolicy; | ||
| import org.springframework.security.web.SecurityFilterChain; | ||
| import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
|
|
||
| @Configuration | ||
| @EnableWebSecurity | ||
| @RequiredArgsConstructor | ||
| public class SecurityConfig { | ||
|
|
||
| private final JwtTokenProvider jwtTokenProvider; | ||
| private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; | ||
| private final JwtAccessDeniedHandler jwtAccessDeniedHandler; | ||
|
|
||
| @Bean | ||
|
kimyw1018 marked this conversation as resolved.
Resolved
|
||
| public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { | ||
| http | ||
| .csrf(AbstractHttpConfigurer::disable) | ||
| .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) | ||
| .exceptionHandling(exception -> exception | ||
| .authenticationEntryPoint(jwtAuthenticationEntryPoint) | ||
| .accessDeniedHandler(jwtAccessDeniedHandler) | ||
| ) | ||
| .authorizeHttpRequests(auth -> auth | ||
| .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/api/v1/auth/**").permitAll() | ||
|
kimyw1018 marked this conversation as resolved.
Resolved
|
||
| .anyRequest().authenticated() | ||
| ) | ||
| .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); | ||
|
|
||
| return http.build(); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package com.mr.global.security; | ||
|
|
||
| import com.mr.global.apipayload.code.CommonStatus; | ||
| import com.mr.global.apipayload.exception.GeneralException; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.core.context.SecurityContextHolder; | ||
|
|
||
| public class SecurityUtil { | ||
|
|
||
| private SecurityUtil() { | ||
| } | ||
|
|
||
| public static Long getCurrentUserId() { | ||
| final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); | ||
|
|
||
| if (authentication == null || authentication.getName() == null || authentication.getName().equals("anonymousUser")) { | ||
|
kimyw1018 marked this conversation as resolved.
Resolved
|
||
| throw new GeneralException(CommonStatus.UNAUTHORIZED); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 인증 정보가 없을 때 유입될 수 있는 anonymousUser 상황까지 놓치지 않고 꼼꼼하게 예외 처리해 주셨네요. |
||
| } | ||
|
|
||
| try { | ||
| return Long.parseLong(authentication.getName()); | ||
| } catch (NumberFormatException e) { | ||
| throw new GeneralException(CommonStatus.UNAUTHORIZED); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SecurityUtil에서 던지는
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 말씀해주신 대로 SecurityUtil은 컨트롤러/서비스 레이어에서 실행돼서 시큐리티 필터의JwtAuthenticationEntryPoint가 아닌, 전역 예외처리에서 GeneralException을 가로채게 됩니다. 현재 GlobalExceptionHandler 에서 CommonStatus.UNAUTHORIZED 내부의 HttpStatus.UNAUTHORIZED, ApiResponse를 추출하여 HTTP Status 401로 반환하도록 구현되어 있습니다! 정상 반환되는지 재검증 완료했습니다
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 수고하셨습니당!! |
||
| } | ||
| } | ||
| } | ||
|
kimyw1018 marked this conversation as resolved.
Resolved
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| package com.mr.global.security.jwt; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.mr.global.apipayload.ApiResponse; | ||
| import com.mr.global.apipayload.code.CommonStatus; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import org.springframework.http.MediaType; | ||
| import org.springframework.security.access.AccessDeniedException; | ||
| import org.springframework.security.web.access.AccessDeniedHandler; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| @Component | ||
| public class JwtAccessDeniedHandler implements AccessDeniedHandler { | ||
|
|
||
| private final ObjectMapper objectMapper = new ObjectMapper(); | ||
|
|
||
| @Override | ||
| public void handle(HttpServletRequest request, HttpServletResponse response, | ||
| AccessDeniedException accessDeniedException) throws IOException { | ||
|
|
||
| // 403 Forbidden 팀 공통 JSON 응답 반환 | ||
| response.setContentType(MediaType.APPLICATION_JSON_VALUE); | ||
| response.setCharacterEncoding("UTF-8"); | ||
| response.setStatus(HttpServletResponse.SC_FORBIDDEN); | ||
|
|
||
| ApiResponse<Object> apiResponse = ApiResponse.onFailure( | ||
| CommonStatus.FORBIDDEN.getCode(), | ||
| CommonStatus.FORBIDDEN.getMessage(), | ||
| null | ||
| ); | ||
|
|
||
| response.getWriter().write(objectMapper.writeValueAsString(apiResponse)); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| package com.mr.global.security.jwt; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.mr.global.apipayload.ApiResponse; | ||
| import com.mr.global.apipayload.code.CommonStatus; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import org.springframework.http.MediaType; | ||
| import org.springframework.security.core.AuthenticationException; | ||
| import org.springframework.security.web.AuthenticationEntryPoint; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| @Component | ||
| public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { | ||
|
|
||
| private final ObjectMapper objectMapper = new ObjectMapper(); | ||
|
|
||
| @Override | ||
| public void commence(HttpServletRequest request, HttpServletResponse response, | ||
| AuthenticationException authException) throws IOException { | ||
|
|
||
| // 401 Unauthorized 팀 공통 JSON 응답 반환 | ||
| response.setContentType(MediaType.APPLICATION_JSON_VALUE); | ||
| response.setCharacterEncoding("UTF-8"); | ||
| response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); | ||
|
|
||
| ApiResponse<Object> apiResponse = ApiResponse.onFailure( | ||
| CommonStatus.UNAUTHORIZED.getCode(), | ||
| CommonStatus.UNAUTHORIZED.getMessage(), | ||
| null | ||
| ); | ||
|
|
||
| response.getWriter().write(objectMapper.writeValueAsString(apiResponse)); | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.