-
Notifications
You must be signed in to change notification settings - Fork 3
OAuth Github 기능 구현하기 #158
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
Open
ESJung95
wants to merge
7
commits into
develop
Choose a base branch
from
feat/oauth-github
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
OAuth Github 기능 구현하기 #158
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c0b787a
feat: OAuth2 의존성 추가
ESJung95 97d13f4
feat: OAuth2 GitHub 인증 기능 구현
ESJung95 6c770b4
feat: 비밀번호 encoder 분리
ESJung95 0e26dde
feat: OAuth2.0 Response 추가
ESJung95 cc431b7
feat: GitHub OAuth 인증 서비스 구현
ESJung95 904459c
feat: 에러 코드 추가
ESJung95 2ed9ca7
feat: GitHub OAuth 인증 성공 핸들러 구현
ESJung95 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
64 changes: 64 additions & 0 deletions
64
src/main/java/com/ctrls/auto_enter_view/component/OAuth2GithubSuccessHandler.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,64 @@ | ||
| package com.ctrls.auto_enter_view.component; | ||
|
|
||
| import com.ctrls.auto_enter_view.entity.CandidateEntity; | ||
| import com.ctrls.auto_enter_view.enums.UserRole; | ||
| import com.ctrls.auto_enter_view.repository.CandidateRepository; | ||
| import com.ctrls.auto_enter_view.security.JwtTokenProvider; | ||
| import com.ctrls.auto_enter_view.util.RandomGenerator; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import java.io.IOException; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.security.oauth2.core.user.OAuth2User; | ||
| import org.springframework.security.web.authentication.AuthenticationSuccessHandler; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| @Slf4j | ||
| public class OAuth2GithubSuccessHandler implements AuthenticationSuccessHandler { | ||
|
|
||
| private final CandidateRepository candidateRepository; | ||
| private final JwtTokenProvider jwtTokenProvider; | ||
| private final KeyGenerator keyGenerator; | ||
| private final PasswordEncoder passwordEncoder; | ||
|
|
||
| @Override | ||
| @Transactional | ||
| public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, | ||
| Authentication authentication) throws IOException, ServletException { | ||
| OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal(); | ||
| String email = oAuth2User.getAttribute("email"); | ||
| String name = oAuth2User.getAttribute("name"); | ||
|
|
||
| CandidateEntity candidate = candidateRepository.findByEmail(email) | ||
| .orElseGet(() -> createNewCandidate(email, name)); | ||
|
|
||
| String token = jwtTokenProvider.generateToken(candidate.getEmail(), candidate.getRole()); | ||
|
|
||
| response.setHeader("Authorization", "Bearer " + token); | ||
| response.sendRedirect("/common/job-postings?page=1"); | ||
| } | ||
|
|
||
| private CandidateEntity createNewCandidate(String email, String name) { | ||
|
|
||
| String randomPassword = RandomGenerator.generateTemporaryPassword(); | ||
| String encodedPassword = passwordEncoder.encode(randomPassword); | ||
|
|
||
| CandidateEntity newCandidate = CandidateEntity.builder() | ||
| .candidateKey(keyGenerator.generateKey()) | ||
| .email(email) | ||
| .name(name) | ||
| .password(encodedPassword) | ||
| .phoneNumber("temp_number") | ||
| .role(UserRole.ROLE_CANDIDATE) | ||
| .build(); | ||
|
|
||
| return candidateRepository.save(newCandidate); | ||
| } | ||
| } |
15 changes: 15 additions & 0 deletions
15
src/main/java/com/ctrls/auto_enter_view/config/PasswordEncoderConfig.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,15 @@ | ||
| package com.ctrls.auto_enter_view.config; | ||
|
|
||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
|
|
||
| @Configuration | ||
| public class PasswordEncoderConfig { | ||
|
|
||
| @Bean | ||
| public PasswordEncoder passwordEncoder() { | ||
| return new BCryptPasswordEncoder(); | ||
| } | ||
| } | ||
19 changes: 19 additions & 0 deletions
19
src/main/java/com/ctrls/auto_enter_view/dto/auth/GithubOAuthDto.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.ctrls.auto_enter_view.dto.auth; | ||
|
|
||
| import lombok.AllArgsConstructor; | ||
| import lombok.Builder; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
|
|
||
| public class GithubOAuthDto { | ||
|
|
||
| @Getter | ||
| @NoArgsConstructor | ||
| @AllArgsConstructor | ||
| @Builder | ||
| public static class Response { | ||
| private String candidateKey; | ||
| private String email; | ||
| private String name; | ||
| } | ||
| } |
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
92 changes: 92 additions & 0 deletions
92
src/main/java/com/ctrls/auto_enter_view/service/GithubOAuthService.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,92 @@ | ||
| package com.ctrls.auto_enter_view.service; | ||
|
|
||
| import com.ctrls.auto_enter_view.enums.ErrorCode; | ||
| import com.ctrls.auto_enter_view.enums.UserRole; | ||
| import com.ctrls.auto_enter_view.exception.CustomException; | ||
| import com.fasterxml.jackson.core.JsonProcessingException; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import java.util.Collections; | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.HttpEntity; | ||
| import org.springframework.http.HttpHeaders; | ||
| import org.springframework.http.HttpMethod; | ||
| import org.springframework.http.ResponseEntity; | ||
| 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.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.web.client.RestTemplate; | ||
|
|
||
| // GitHub OAuth 인증을 처리하는 서비스 클래스 | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class GithubOAuthService extends DefaultOAuth2UserService { | ||
|
|
||
| // OAuth2UserRequest를 기반으로 사용자 정보를 로드하는 메서드 | ||
| @Override | ||
| public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { | ||
| // 부모 클래스의 loadUser 메서드를 호출하여 기본 OAuth2User 객체를 얻음 | ||
| OAuth2User oAuth2User = super.loadUser(userRequest); | ||
|
|
||
| // GitHub API에 접근하기 위한 액세스 토큰 설정 | ||
| String token = userRequest.getAccessToken().getTokenValue(); | ||
| HttpHeaders headers = new HttpHeaders(); | ||
| headers.setBearerAuth(token); | ||
| HttpEntity<String> entity = new HttpEntity<>(headers); | ||
|
|
||
| RestTemplate restTemplate = new RestTemplate(); | ||
|
|
||
| // GitHub API를 통해 사용자의 이메일 정보 가져오기 | ||
| ResponseEntity<String> emailResponse = restTemplate.exchange("https://api.github.com/user/emails", HttpMethod.GET, entity, String.class); | ||
| String email = extractEmail(emailResponse); | ||
|
|
||
| // GitHub API를 통해 사용자 정보 가져오기 | ||
| ResponseEntity<String> userResponse = restTemplate.exchange("https://api.github.com/user", HttpMethod.GET, entity, String.class); | ||
| String name = extractName(userResponse); | ||
|
|
||
| // 이메일이 없으면 예외 발생 | ||
| if (email == null) { | ||
| throw new CustomException(ErrorCode.EMAIL_NOT_FOUND); | ||
| } | ||
|
|
||
| // 이름이 없으면 예외 발생 | ||
| if (name == null) { | ||
| throw new CustomException(ErrorCode.NAME_NOT_FOUND); | ||
| } | ||
|
|
||
| // 사용자 정보를 OAuth2User 형태로 반환하기 위해 속성 맵 생성 | ||
| Map<String, Object> attributes = new HashMap<>(oAuth2User.getAttributes()); | ||
| attributes.put("email", email); | ||
| attributes.put("name", name); | ||
|
|
||
| // DefaultOAuth2User 객체 생성 및 반환 | ||
| return new DefaultOAuth2User( | ||
| Collections.singleton(new SimpleGrantedAuthority(UserRole.ROLE_CANDIDATE.name())), | ||
| attributes, | ||
| "id" | ||
| ); | ||
| } | ||
|
|
||
| // GitHub API 응답에서 이메일 추출하는 메서드 | ||
| private String extractEmail(ResponseEntity<String> response) { | ||
| try { | ||
| return new ObjectMapper().readTree(response.getBody()).get(0).get("email").asText(); | ||
| } catch (JsonProcessingException e) { | ||
| throw new CustomException(ErrorCode.JSON_PROCESSING_ERROR); | ||
| } | ||
| } | ||
|
|
||
| // GitHub API 응답에서 이름 추출하는 메서드 | ||
| private String extractName(ResponseEntity<String> response) { | ||
| try { | ||
| return new ObjectMapper().readTree(response.getBody()).get("name").asText(); | ||
| } catch (JsonProcessingException e) { | ||
| throw new CustomException(ErrorCode.JSON_PROCESSING_ERROR); | ||
| } | ||
| } | ||
| } |
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.
저도 은선님께서 말씀해주신 것처럼 PasswordEncoder를 Config로 따로 뺐더니 순환 참조 문제가 해결되었습니다! 감사해요 ㅎㅎ