Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rj93/a2acfcdc583743579fde8e7a3acbc67e to your computer and use it in GitHub Desktop.
Save rj93/a2acfcdc583743579fde8e7a3acbc67e to your computer and use it in GitHub Desktop.
Hello Controller, that reaches out to Reddit to obtain the username.
@RestController
public class HelloController {
private final ReactiveOAuth2AuthorizedClientService authorizedClientService;
private final WebClient webClient = WebClient.builder().build();
public HelloController(ReactiveOAuth2AuthorizedClientService authorizedClientService) {
this.authorizedClientService = authorizedClientService;
}
@GetMapping
public Mono<String> hello() {
return ReactiveSecurityContextHolder.getContext()
.map(securityContext -> securityContext.getAuthentication().getName())
.flatMap(this::getAccessToken)
.flatMap(this::getUsername)
.map(name -> "Hello, " + name);
}
private Mono<String> getAccessToken(String name) {
return authorizedClientService
.loadAuthorizedClient("reddit", name)
.map(client -> client.getAccessToken().getTokenValue());
}
private Mono<String> getUsername(String token) {
String bearerToken = "bearer " + token;
return webClient.get()
.uri("https://oauth.reddit.com/api/v1/me")
.header(HttpHeaders.AUTHORIZATION, bearerToken)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {})
.map(responseBody -> "u/" + responseBody.get("name"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment