-
Notifications
You must be signed in to change notification settings - Fork 0
Google OAuth2 소셜 로그인 및 JWT 발급 기능 구현 #101
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
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
24 changes: 24 additions & 0 deletions
24
src/main/java/com/sofa/linkiving/security/auth/code/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,24 @@ | ||
| package com.sofa.linkiving.security.auth.code; | ||
|
|
||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| import com.sofa.linkiving.global.error.code.ErrorCode; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public enum AuthErrorCode implements ErrorCode { | ||
|
|
||
| LOGIN_FAILED(HttpStatus.UNAUTHORIZED, "A-000", "로그인에 실패했습니다."), | ||
| INVALID_SOCIAL_PROVIDER(HttpStatus.BAD_REQUEST, "A-001", "지원하지 않는 소셜 로그인입니다."), | ||
| AUTHORIZATION_REQUEST_NOT_FOUND(HttpStatus.BAD_REQUEST, "A-002", "인증 요청 정보를 찾을 수 없습니다. (쿠키 누락 등)"), | ||
| USER_CANCELLED(HttpStatus.BAD_REQUEST, "A-003", "사용자가 로그인을 취소했습니다."), | ||
| PROVIDER_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "A-100", "소셜 공급자(Google) 서버 오류입니다."), | ||
| INTERNAL_AUTH_SERVICE_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "A-101", "인증 처리 중 서버 내부 오류가 발생했습니다."); | ||
|
|
||
| private final HttpStatus status; | ||
| private final String code; | ||
| private final String message; | ||
| } |
10 changes: 10 additions & 0 deletions
10
src/main/java/com/sofa/linkiving/security/auth/config/OAuth2Properties.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.sofa.linkiving.security.auth.config; | ||
|
|
||
| import org.springframework.boot.context.properties.ConfigurationProperties; | ||
|
|
||
| @ConfigurationProperties(prefix = "app.oauth2") | ||
| public record OAuth2Properties( | ||
| String successRedirectUrl, | ||
| String failureRedirectUrl | ||
| ) { | ||
| } |
57 changes: 57 additions & 0 deletions
57
src/main/java/com/sofa/linkiving/security/auth/handler/OAuth2FailureHandler.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,57 @@ | ||
| package com.sofa.linkiving.security.auth.handler; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| import org.springframework.security.core.AuthenticationException; | ||
| import org.springframework.security.oauth2.core.OAuth2AuthenticationException; | ||
| import org.springframework.security.oauth2.core.OAuth2Error; | ||
| import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.util.UriComponentsBuilder; | ||
|
|
||
| import com.sofa.linkiving.global.error.code.ErrorCode; | ||
| import com.sofa.linkiving.global.error.exception.BusinessException; | ||
| import com.sofa.linkiving.security.auth.code.AuthErrorCode; | ||
| import com.sofa.linkiving.security.auth.config.OAuth2Properties; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class OAuth2FailureHandler extends SimpleUrlAuthenticationFailureHandler { | ||
|
|
||
| private final OAuth2Properties oauth2Properties; | ||
|
|
||
| @Override | ||
| public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, | ||
| AuthenticationException exception) throws IOException { | ||
|
|
||
| ErrorCode errorCode = AuthErrorCode.LOGIN_FAILED; | ||
| Throwable cause = exception.getCause(); | ||
|
|
||
| if (cause instanceof BusinessException businessException) { | ||
| errorCode = businessException.getErrorCode(); | ||
|
|
||
| } else if (exception instanceof OAuth2AuthenticationException oauthException) { | ||
| OAuth2Error error = oauthException.getError(); | ||
| errorCode = determineAuthErrorCode(error.getErrorCode()); | ||
| } | ||
|
|
||
| String targetUrl = UriComponentsBuilder.fromUriString(oauth2Properties.failureRedirectUrl()) | ||
| .queryParam("code", errorCode.getCode()) | ||
| .build().toUriString(); | ||
|
|
||
| getRedirectStrategy().sendRedirect(request, response, targetUrl); | ||
| } | ||
|
|
||
| private AuthErrorCode determineAuthErrorCode(String providerErrorCode) { | ||
| return switch (providerErrorCode) { | ||
| case "access_denied" -> AuthErrorCode.USER_CANCELLED; | ||
| case "invalid_client", "invalid_request" -> AuthErrorCode.INVALID_SOCIAL_PROVIDER; | ||
| case "server_error", "temporarily_unavailable" -> AuthErrorCode.PROVIDER_SERVER_ERROR; | ||
| default -> AuthErrorCode.LOGIN_FAILED; | ||
| }; | ||
| } | ||
| } |
62 changes: 62 additions & 0 deletions
62
src/main/java/com/sofa/linkiving/security/auth/handler/OAuth2SuccessHandler.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,62 @@ | ||
| package com.sofa.linkiving.security.auth.handler; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| import org.springframework.http.HttpHeaders; | ||
| import org.springframework.http.ResponseCookie; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.oauth2.core.user.OAuth2User; | ||
| import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import com.sofa.linkiving.security.auth.config.OAuth2Properties; | ||
| import com.sofa.linkiving.security.jwt.JwtProperties; | ||
| import com.sofa.linkiving.security.jwt.JwtTokenProvider; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @RequiredArgsConstructor | ||
| @Component | ||
| public class OAuth2SuccessHandler extends SimpleUrlAuthenticationSuccessHandler { | ||
|
|
||
| private final JwtTokenProvider jwtTokenProvider; | ||
| private final OAuth2Properties oauth2Properties; | ||
| private final JwtProperties jwtProperties; | ||
|
|
||
| @Override | ||
| public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, | ||
| Authentication authentication) throws IOException { | ||
|
|
||
| OAuth2User oAuth2User = (OAuth2User)authentication.getPrincipal(); | ||
| String email = oAuth2User.getAttribute("email"); | ||
|
|
||
| String accessToken = jwtTokenProvider.createAccessToken(email); | ||
| String refreshToken = jwtTokenProvider.createRefreshToken(email); | ||
|
|
||
| int accessExp = (int)(jwtProperties.accessTokenValidTime() / 1000); | ||
| int refreshExp = (int)(jwtProperties.refreshTokenValidTime() / 1000); | ||
|
|
||
| addCookie(request, response, "accessToken", accessToken, accessExp); | ||
| addCookie(request, response, "refreshToken", refreshToken, refreshExp); | ||
|
|
||
| String targetUrl = oauth2Properties.successRedirectUrl(); | ||
| getRedirectStrategy().sendRedirect(request, response, targetUrl); | ||
| } | ||
|
|
||
| private void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, | ||
| int maxAge) { | ||
| String domain = request.getServerName(); | ||
| boolean isLocal = "localhost".equals(domain) || "127.0.0.1".equals(domain); | ||
|
|
||
| ResponseCookie cookie = ResponseCookie.from(name, value) | ||
| .path("/") | ||
| .maxAge(maxAge) | ||
| .httpOnly(!isLocal) | ||
| .secure(!isLocal) | ||
| .sameSite("Lax") | ||
| .build(); | ||
| response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString()); | ||
| } | ||
| } | ||
ckdals4600 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
19 changes: 19 additions & 0 deletions
19
src/main/java/com/sofa/linkiving/security/auth/info/GoogleOAuth2User.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.sofa.linkiving.security.auth.info; | ||
|
|
||
| import java.util.Map; | ||
|
|
||
| public record GoogleOAuth2User( | ||
| Map<String, Object> attributes, | ||
| String name, | ||
| String email, | ||
| String picture | ||
| ) { | ||
| public GoogleOAuth2User(Map<String, Object> attributes) { | ||
| this( | ||
| attributes, | ||
| (String)attributes.get("name"), | ||
| (String)attributes.get("email"), | ||
| (String)attributes.get("picture") | ||
| ); | ||
| } | ||
| } |
43 changes: 43 additions & 0 deletions
43
src/main/java/com/sofa/linkiving/security/auth/service/CustomOAuth2UserService.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,43 @@ | ||
| package com.sofa.linkiving.security.auth.service; | ||
|
|
||
| import java.util.Collections; | ||
|
|
||
| import org.springframework.security.core.authority.SimpleGrantedAuthority; | ||
| import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; | ||
| import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; | ||
| import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; | ||
| import org.springframework.security.oauth2.core.OAuth2AuthenticationException; | ||
| import org.springframework.security.oauth2.core.user.DefaultOAuth2User; | ||
| import org.springframework.security.oauth2.core.user.OAuth2User; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| import com.sofa.linkiving.domain.member.entity.Member; | ||
| import com.sofa.linkiving.domain.member.service.MemberCommandService; | ||
| import com.sofa.linkiving.security.auth.info.GoogleOAuth2User; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @RequiredArgsConstructor | ||
| @Service | ||
| public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> { | ||
|
|
||
| private final MemberCommandService memberCommandService; | ||
|
|
||
| @Override | ||
| @Transactional | ||
| public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { | ||
| OAuth2UserService<OAuth2UserRequest, OAuth2User> delegate = new DefaultOAuth2UserService(); | ||
| OAuth2User oAuth2User = delegate.loadUser(userRequest); | ||
|
|
||
| GoogleOAuth2User googleUser = new GoogleOAuth2User(oAuth2User.getAttributes()); | ||
|
|
||
| Member member = memberCommandService.createOrUpdate(googleUser.email()); | ||
|
|
||
| return new DefaultOAuth2User( | ||
| Collections.singleton(new SimpleGrantedAuthority("ROLE_" + member.getRole().name())), | ||
| googleUser.attributes(), | ||
| "sub" | ||
| ); | ||
| } | ||
| } |
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
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.
Uh oh!
There was an error while loading. Please reload this page.