auth media
This commit is contained in:
@@ -0,0 +1,48 @@
|
|||||||
|
package com.posthub.gateway.security;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.security.oauth2.client.userinfo.DefaultReactiveOAuth2UserService;
|
||||||
|
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
|
||||||
|
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
|
||||||
|
import org.springframework.security.oauth2.core.user.OAuth2User;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class GitHubEmailFetcher extends DefaultReactiveOAuth2UserService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<OAuth2User> loadUser(OAuth2UserRequest userRequest) {
|
||||||
|
return super.loadUser(userRequest)
|
||||||
|
.flatMap(user -> {
|
||||||
|
if (user.getAttribute("email") != null) {
|
||||||
|
return Mono.just(user);
|
||||||
|
}
|
||||||
|
if (!"github".equals(userRequest.getClientRegistration().getRegistrationId())) {
|
||||||
|
return Mono.just(user);
|
||||||
|
}
|
||||||
|
String token = userRequest.getAccessToken().getTokenValue();
|
||||||
|
return WebClient.create("https://api.github.com")
|
||||||
|
.get()
|
||||||
|
.uri("/user/emails")
|
||||||
|
.headers(h -> h.setBearerAuth(token))
|
||||||
|
.retrieve()
|
||||||
|
.bodyToFlux(Map.class)
|
||||||
|
.filter(e -> Boolean.TRUE.equals(e.get("primary")))
|
||||||
|
.next()
|
||||||
|
.map(e -> {
|
||||||
|
Map<String, Object> attrs = new HashMap<>(user.getAttributes());
|
||||||
|
attrs.put("email", e.get("email"));
|
||||||
|
return (OAuth2User) new DefaultOAuth2User(
|
||||||
|
user.getAuthorities(), attrs, "id");
|
||||||
|
})
|
||||||
|
.defaultIfEmpty(user);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user