-
Notifications
You must be signed in to change notification settings - Fork 0
feat: 구글 로그인 기능 구현 #18
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
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
9bc9290
feat: docs 생성
sangwon02 78b6580
feat: 구글 로그인 인증 기반 설정
sangwon02 dccad76
feat: 구글 인증 페이지 리다이렉트 API 구현
sangwon02 6e52685
feat: 구글 콜백 처리 API 구현
sangwon02 1b48395
feat: 액세스 토큰 재발급 API 구현
sangwon02 12719af
feat: 로그아웃 API 구현
sangwon02 e485df8
test: 인증 빈 추가에 따른 컨텍스트 테스트 보정
sangwon02 d744ff7
test: 컨텍스트 로드 테스트 정상화
sangwon02 c6b1280
feat: 쿠키 Secure 속성을 환경변수로 분리
sangwon02 4e191fe
fix: OAuth state 쿠키의 SameSite를 Lax로 분리
sangwon02 9d27e6e
feat: Swagger에 Bearer 인증 스킴 추가
sangwon02 edefbc0
docs: 인증 API의 Swagger 노출 범위 정리
sangwon02 73f4f3a
chore: 액세스 토큰 유효기간을 1시간으로 조정
sangwon02 00517f1
merge: develop 최신 변경 병합
sangwon02 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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 |
|---|---|---|
|
|
@@ -50,3 +50,6 @@ logs/ | |
|
|
||
| ### macOS ### | ||
| .DS_Store | ||
|
|
||
| ### Docs ### | ||
| docs/ | ||
This file contains hidden or 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
This file contains hidden or 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
61 changes: 61 additions & 0 deletions
61
src/main/java/com/slatto/domain/auth/client/GoogleOAuthClient.java
This file contains hidden or 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,61 @@ | ||
| package com.slatto.domain.auth.client; | ||
|
|
||
| import com.slatto.domain.auth.client.dto.GoogleTokenResponse; | ||
| import com.slatto.domain.auth.client.dto.GoogleUserInfo; | ||
| import com.slatto.global.config.properties.GoogleOAuthProperties; | ||
| import org.springframework.http.MediaType; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.util.LinkedMultiValueMap; | ||
| import org.springframework.util.MultiValueMap; | ||
| import org.springframework.web.client.RestClient; | ||
| import org.springframework.web.util.UriComponentsBuilder; | ||
|
|
||
| @Component | ||
| public class GoogleOAuthClient { | ||
|
|
||
| private final GoogleOAuthProperties googleOAuthProperties; | ||
| private final RestClient restClient; | ||
|
|
||
| public GoogleOAuthClient(GoogleOAuthProperties googleOAuthProperties, RestClient.Builder restClientBuilder) { | ||
| this.googleOAuthProperties = googleOAuthProperties; | ||
| this.restClient = restClientBuilder.build(); | ||
| } | ||
|
|
||
| public String buildAuthorizationUri(String state) { | ||
| return UriComponentsBuilder.fromUriString(googleOAuthProperties.authorizationUri()) | ||
| .queryParam("client_id", googleOAuthProperties.clientId()) | ||
| .queryParam("redirect_uri", googleOAuthProperties.redirectUri()) | ||
| .queryParam("response_type", "code") | ||
| .queryParam("scope", googleOAuthProperties.scope()) | ||
| .queryParam("state", state) | ||
| .queryParam("access_type", "offline") | ||
| .build() | ||
| .encode() | ||
| .toUriString(); | ||
| } | ||
|
|
||
| public GoogleTokenResponse exchangeCodeForToken(String code) { | ||
| MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); | ||
| form.add("code", code); | ||
| form.add("client_id", googleOAuthProperties.clientId()); | ||
| form.add("client_secret", googleOAuthProperties.clientSecret()); | ||
| form.add("redirect_uri", googleOAuthProperties.redirectUri()); | ||
| form.add("grant_type", "authorization_code"); | ||
|
|
||
| return restClient.post() | ||
| .uri(googleOAuthProperties.tokenUri()) | ||
| .contentType(MediaType.APPLICATION_FORM_URLENCODED) | ||
| .body(form) | ||
| .retrieve() | ||
| .body(GoogleTokenResponse.class); | ||
| } | ||
|
|
||
| public GoogleUserInfo fetchUserInfo(String accessToken) { | ||
| return restClient.get() | ||
| .uri(googleOAuthProperties.userInfoUri()) | ||
| .header("Authorization", "Bearer " + accessToken) | ||
| .retrieve() | ||
| .body(GoogleUserInfo.class); | ||
| } | ||
|
|
||
| } | ||
10 changes: 10 additions & 0 deletions
10
src/main/java/com/slatto/domain/auth/client/dto/GoogleTokenResponse.java
This file contains hidden or 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,10 @@ | ||
| package com.slatto.domain.auth.client.dto; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonProperty; | ||
|
|
||
| public record GoogleTokenResponse( | ||
| @JsonProperty("access_token") String accessToken, | ||
| @JsonProperty("expires_in") Long expiresIn, | ||
| @JsonProperty("token_type") String tokenType | ||
| ) { | ||
| } |
17 changes: 17 additions & 0 deletions
17
src/main/java/com/slatto/domain/auth/client/dto/GoogleUserInfo.java
This file contains hidden or 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,17 @@ | ||
| package com.slatto.domain.auth.client.dto; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonProperty; | ||
|
|
||
| public record GoogleUserInfo( | ||
| String sub, | ||
| String email, | ||
| @JsonProperty("email_verified") Boolean emailVerified, | ||
| String name, | ||
| String picture | ||
| ) { | ||
|
|
||
| public boolean isEmailVerified() { | ||
| return Boolean.TRUE.equals(emailVerified); | ||
| } | ||
|
|
||
| } |
109 changes: 109 additions & 0 deletions
109
src/main/java/com/slatto/domain/auth/controller/AuthController.java
This file contains hidden or 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,109 @@ | ||
| package com.slatto.domain.auth.controller; | ||
|
|
||
| import com.slatto.domain.auth.dto.AccessTokenResponse; | ||
| import com.slatto.domain.auth.service.AuthService; | ||
| import com.slatto.domain.auth.support.AuthCookieFactory; | ||
| import com.slatto.global.response.ApiResponse; | ||
| import com.slatto.global.response.code.CommonSuccessCode; | ||
| import io.swagger.v3.oas.annotations.Hidden; | ||
| import io.swagger.v3.oas.annotations.Operation; | ||
| import io.swagger.v3.oas.annotations.security.SecurityRequirements; | ||
| import io.swagger.v3.oas.annotations.tags.Tag; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.HttpHeaders; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.web.bind.annotation.CookieValue; | ||
| import org.springframework.web.bind.annotation.GetMapping; | ||
| import org.springframework.web.bind.annotation.PostMapping; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RequestParam; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
|
|
||
| import java.net.URI; | ||
|
|
||
| @Tag(name = "Auth", description = "인증 API") | ||
| @RestController | ||
| @RequiredArgsConstructor | ||
| @RequestMapping("/api/v1/auth") | ||
| public class AuthController { | ||
|
|
||
| private final AuthService authService; | ||
| private final AuthCookieFactory authCookieFactory; | ||
|
|
||
| @Operation( | ||
| summary = "구글 로그인 진입", | ||
| description = """ | ||
| 구글 인증 페이지로 302 리다이렉트한다. 인증이 필요 없다. | ||
|
|
||
| `<a href>` 또는 `window.location.href`로 **브라우저를 이동시켜** 호출한다. | ||
| fetch/ajax로 호출하는 API가 아니며, Swagger의 Try it out으로는 동작하지 않는다. | ||
|
|
||
| 성공 시 302로 응답하며, 공통 응답 wrapper를 사용하지 않는다. | ||
| """ | ||
| ) | ||
| @SecurityRequirements | ||
| @GetMapping("/login/google") | ||
| public ResponseEntity<Void> loginWithGoogle( | ||
| @RequestParam(name = "redirectTo", required = false) String redirectTo | ||
| ) { | ||
| AuthService.GoogleLoginEntry entry = authService.createGoogleLoginEntry(redirectTo); | ||
|
|
||
| return ResponseEntity | ||
| .status(302) | ||
| .header(HttpHeaders.SET_COOKIE, authCookieFactory.oauthState(entry.state().toCookieValue()).toString()) | ||
| .location(URI.create(entry.authorizationUri())) | ||
| .build(); | ||
| } | ||
|
|
||
| @Hidden | ||
| @GetMapping("/callback/google") | ||
| public ResponseEntity<Void> handleGoogleCallback( | ||
| @RequestParam(name = "code", required = false) String code, | ||
| @RequestParam(name = "state", required = false) String state, | ||
| @RequestParam(name = "error", required = false) String error, | ||
| @CookieValue(name = "${app.cookie.oauth-state-name}", required = false) String stateCookie | ||
| ) { | ||
| AuthService.GoogleCallbackResult result = authService.handleGoogleCallback(code, state, error, stateCookie); | ||
|
|
||
| ResponseEntity.BodyBuilder builder = ResponseEntity | ||
| .status(302) | ||
| .header(HttpHeaders.SET_COOKIE, authCookieFactory.expiredOauthState().toString()); | ||
|
|
||
| if (result.isSuccess()) { | ||
| builder.header( | ||
| HttpHeaders.SET_COOKIE, | ||
| authCookieFactory.refreshToken(result.refreshToken(), result.refreshTokenMaxAgeSeconds()).toString() | ||
| ); | ||
| } | ||
|
|
||
| return builder | ||
| .location(URI.create(result.redirectUri())) | ||
| .build(); | ||
| } | ||
|
|
||
| @Operation( | ||
| summary = "액세스 토큰 재발급", | ||
| description = "쿠키의 리프레시 토큰으로 새 액세스 토큰을 발급한다. 요청 본문과 Authorization 헤더가 모두 필요 없다." | ||
| ) | ||
| @SecurityRequirements | ||
| @PostMapping("/refresh") | ||
| public ApiResponse<AccessTokenResponse> reissueAccessToken( | ||
| @CookieValue(name = "${app.cookie.refresh-token-name}", required = false) String refreshToken | ||
| ) { | ||
| return ApiResponse.success(CommonSuccessCode.OK, authService.reissueAccessToken(refreshToken)); | ||
| } | ||
|
|
||
| @Operation(summary = "로그아웃", description = "서버에 저장된 리프레시 토큰을 무효화하고 쿠키를 삭제한다.") | ||
| @PostMapping("/logout") | ||
| public ResponseEntity<ApiResponse<Void>> logout( | ||
| @CookieValue(name = "${app.cookie.refresh-token-name}", required = false) String refreshToken | ||
| ) { | ||
| authService.logout(refreshToken); | ||
|
|
||
| return ResponseEntity | ||
| .ok() | ||
| .header(HttpHeaders.SET_COOKIE, authCookieFactory.expiredRefreshToken().toString()) | ||
| .body(ApiResponse.<Void>success(CommonSuccessCode.OK, null)); | ||
| } | ||
|
|
||
| } |
4 changes: 4 additions & 0 deletions
4
src/main/java/com/slatto/domain/auth/dto/AccessTokenResponse.java
This file contains hidden or 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,4 @@ | ||
| package com.slatto.domain.auth.dto; | ||
|
|
||
| public record AccessTokenResponse(String accessToken) { | ||
| } |
50 changes: 50 additions & 0 deletions
50
src/main/java/com/slatto/domain/auth/entity/RefreshToken.java
This file contains hidden or 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,50 @@ | ||
| package com.slatto.domain.auth.entity; | ||
|
|
||
| import com.slatto.domain.common.entity.BaseEntity; | ||
| import com.slatto.domain.user.entity.Users; | ||
| import jakarta.persistence.*; | ||
| import lombok.AccessLevel; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| @Entity | ||
| @Table( | ||
| name = "refresh_token", | ||
| indexes = @Index(name = "idx_refresh_token_user_id", columnList = "user_id") | ||
| ) | ||
| @Getter | ||
| @NoArgsConstructor(access = AccessLevel.PROTECTED) | ||
| public class RefreshToken extends BaseEntity { | ||
|
|
||
| @Id | ||
| @GeneratedValue(strategy = GenerationType.IDENTITY) | ||
| @Column(name = "id", nullable = false) | ||
| private Long id; | ||
|
|
||
| @ManyToOne(fetch = FetchType.LAZY, optional = false) | ||
| @JoinColumn(name = "user_id", nullable = false) | ||
| private Users user; | ||
|
|
||
| @Column(name = "token", nullable = false, length = 512, unique = true) | ||
| private String token; | ||
|
Comment on lines
+30
to
+31
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 | 🟠 Major | 🏗️ Heavy lift 리프레시 토큰을 평문으로 저장하지 마세요. Line 30은 재사용 가능한 bearer 토큰을 그대로 저장합니다. DB 읽기 권한 유출만으로 세션 탈취가 가능하므로, 서버 비밀키 기반 HMAC 다이제스트를 저장하고 조회·삭제 시에도 쿠키 토큰을 동일하게 다이제스트하세요. 🤖 Prompt for AI Agents |
||
|
|
||
| @Column(name = "expires_at", nullable = false) | ||
| private LocalDateTime expiresAt; | ||
|
|
||
| private RefreshToken(Users user, String token, LocalDateTime expiresAt) { | ||
| this.user = user; | ||
| this.token = token; | ||
| this.expiresAt = expiresAt; | ||
| } | ||
|
|
||
| public static RefreshToken issue(Users user, String token, LocalDateTime expiresAt) { | ||
| return new RefreshToken(user, token, expiresAt); | ||
| } | ||
|
|
||
| public boolean isExpired(LocalDateTime now) { | ||
| return expiresAt.isBefore(now); | ||
| } | ||
|
|
||
| } | ||
23 changes: 23 additions & 0 deletions
23
src/main/java/com/slatto/domain/auth/exception/AuthErrorCode.java
This file contains hidden or 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,23 @@ | ||
| package com.slatto.domain.auth.exception; | ||
|
|
||
| import com.slatto.global.response.code.BaseCode; | ||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public enum AuthErrorCode implements BaseCode { | ||
|
|
||
| INVALID_REFRESH_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH401", "리프레시 토큰이 만료되었거나 유효하지 않습니다."); | ||
|
|
||
| private final HttpStatus httpStatus; | ||
| private final String code; | ||
| private final String message; | ||
|
|
||
| @Override | ||
| public boolean isSuccess() { | ||
| return false; | ||
| } | ||
|
|
||
| } |
19 changes: 19 additions & 0 deletions
19
src/main/java/com/slatto/domain/auth/repository/RefreshTokenRepository.java
This file contains hidden or 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,19 @@ | ||
| package com.slatto.domain.auth.repository; | ||
|
|
||
| import com.slatto.domain.auth.entity.RefreshToken; | ||
| import com.slatto.domain.user.entity.Users; | ||
| import org.springframework.data.jpa.repository.JpaRepository; | ||
| import org.springframework.stereotype.Repository; | ||
|
|
||
| import java.util.Optional; | ||
|
|
||
| @Repository | ||
| public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> { | ||
|
|
||
| Optional<RefreshToken> findByToken(String token); | ||
|
|
||
| void deleteByToken(String token); | ||
|
|
||
| void deleteByUser(Users user); | ||
|
|
||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: SLAT-TO/SLATE-TO-BE
Length of output: 4652
🏁 Script executed:
Repository: SLAT-TO/SLATE-TO-BE
Length of output: 12208
Google OAuth RestClient에 타임아웃을 추가하세요.
GoogleOAuthClient는RestClient.Builder를 바로build()만 하고 있어, Google 토큰/사용자정보 호출에 연결·응답 제한 시간이 없습니다.YoutubeApiClient처럼 이 클라이언트에도 connect/read timeout을 넣거나 공통 builder에 기본 타임아웃을 설정하세요.🤖 Prompt for AI Agents