|
| 1 | +package org.nkcoder.user.infrastructure.security; |
| 2 | + |
| 3 | +import java.net.URI; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | +import org.slf4j.Logger; |
| 8 | +import org.slf4j.LoggerFactory; |
| 9 | +import org.springframework.core.ParameterizedTypeReference; |
| 10 | +import org.springframework.http.HttpHeaders; |
| 11 | +import org.springframework.http.HttpMethod; |
| 12 | +import org.springframework.http.RequestEntity; |
| 13 | +import org.springframework.http.ResponseEntity; |
| 14 | +import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; |
| 15 | +import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; |
| 16 | +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; |
| 17 | +import org.springframework.security.oauth2.core.user.DefaultOAuth2User; |
| 18 | +import org.springframework.security.oauth2.core.user.OAuth2User; |
| 19 | +import org.springframework.stereotype.Component; |
| 20 | +import org.springframework.web.client.RestTemplate; |
| 21 | + |
| 22 | +/** |
| 23 | + * Custom OAuth2UserService that fetches additional user info (like email) from providers that don't include it in the |
| 24 | + * standard user info response. |
| 25 | + */ |
| 26 | +@Component |
| 27 | +public class CustomOAuth2UserService extends DefaultOAuth2UserService { |
| 28 | + |
| 29 | + private static final Logger logger = LoggerFactory.getLogger(CustomOAuth2UserService.class); |
| 30 | + private static final String GITHUB_EMAILS_URL = "https://api.github.com/user/emails"; |
| 31 | + |
| 32 | + private final RestTemplate restTemplate = new RestTemplate(); |
| 33 | + |
| 34 | + @Override |
| 35 | + public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { |
| 36 | + OAuth2User oAuth2User = super.loadUser(userRequest); |
| 37 | + |
| 38 | + String registrationId = userRequest.getClientRegistration().getRegistrationId(); |
| 39 | + |
| 40 | + if ("github".equalsIgnoreCase(registrationId)) { |
| 41 | + return enrichGitHubUser(userRequest, oAuth2User); |
| 42 | + } |
| 43 | + |
| 44 | + return oAuth2User; |
| 45 | + } |
| 46 | + |
| 47 | + private OAuth2User enrichGitHubUser(OAuth2UserRequest userRequest, OAuth2User oAuth2User) { |
| 48 | + String email = oAuth2User.getAttribute("email"); |
| 49 | + |
| 50 | + if (email == null || email.isBlank()) { |
| 51 | + logger.debug("GitHub user email not in attributes, fetching from /user/emails"); |
| 52 | + email = fetchGitHubPrimaryEmail(userRequest.getAccessToken().getTokenValue()); |
| 53 | + } |
| 54 | + |
| 55 | + if (email != null) { |
| 56 | + // Create new attributes map with email included |
| 57 | + Map<String, Object> attributes = new HashMap<>(oAuth2User.getAttributes()); |
| 58 | + attributes.put("email", email); |
| 59 | + |
| 60 | + return new DefaultOAuth2User( |
| 61 | + oAuth2User.getAuthorities(), |
| 62 | + attributes, |
| 63 | + userRequest |
| 64 | + .getClientRegistration() |
| 65 | + .getProviderDetails() |
| 66 | + .getUserInfoEndpoint() |
| 67 | + .getUserNameAttributeName()); |
| 68 | + } |
| 69 | + |
| 70 | + return oAuth2User; |
| 71 | + } |
| 72 | + |
| 73 | + private String fetchGitHubPrimaryEmail(String accessToken) { |
| 74 | + try { |
| 75 | + HttpHeaders headers = new HttpHeaders(); |
| 76 | + headers.setBearerAuth(accessToken); |
| 77 | + headers.set("Accept", "application/vnd.github+json"); |
| 78 | + |
| 79 | + RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, URI.create(GITHUB_EMAILS_URL)); |
| 80 | + |
| 81 | + ResponseEntity<List<Map<String, Object>>> response = |
| 82 | + restTemplate.exchange(request, new ParameterizedTypeReference<>() {}); |
| 83 | + |
| 84 | + List<Map<String, Object>> emails = response.getBody(); |
| 85 | + if (emails == null || emails.isEmpty()) { |
| 86 | + logger.warn("No emails returned from GitHub API"); |
| 87 | + return null; |
| 88 | + } |
| 89 | + |
| 90 | + // Find primary email, or first verified email, or first email |
| 91 | + return emails.stream() |
| 92 | + .filter(e -> Boolean.TRUE.equals(e.get("primary"))) |
| 93 | + .map(e -> (String) e.get("email")) |
| 94 | + .findFirst() |
| 95 | + .orElseGet(() -> emails.stream() |
| 96 | + .filter(e -> Boolean.TRUE.equals(e.get("verified"))) |
| 97 | + .map(e -> (String) e.get("email")) |
| 98 | + .findFirst() |
| 99 | + .orElseGet(() -> (String) emails.get(0).get("email"))); |
| 100 | + |
| 101 | + } catch (Exception e) { |
| 102 | + logger.error("Failed to fetch GitHub emails: {}", e.getMessage()); |
| 103 | + return null; |
| 104 | + } |
| 105 | + } |
| 106 | +} |
0 commit comments