OAuth2WebClientController.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright 2020 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package example;
  17. import reactor.core.publisher.Mono;
  18. import org.springframework.stereotype.Controller;
  19. import org.springframework.ui.Model;
  20. import org.springframework.web.bind.annotation.GetMapping;
  21. import org.springframework.web.bind.annotation.RequestMapping;
  22. import org.springframework.web.reactive.function.client.WebClient;
  23. import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId;
  24. /**
  25. * A controller that demonstrates how to use WebClient with OAuth.
  26. *
  27. * @author Joe Grandja
  28. * @author Rob Winch
  29. */
  30. @Controller
  31. @RequestMapping(path = { "/webclient", "/public/webclient" })
  32. public class OAuth2WebClientController {
  33. private final WebClient webClient;
  34. public OAuth2WebClientController(WebClient webClient) {
  35. this.webClient = webClient;
  36. }
  37. @GetMapping("/explicit")
  38. String explicit(Model model) {
  39. // @formatter:off
  40. Mono<String> body = this.webClient
  41. .get()
  42. .attributes(clientRegistrationId("client-id"))
  43. .retrieve()
  44. .bodyToMono(String.class);
  45. // @formatter:on
  46. model.addAttribute("body", body);
  47. return "response";
  48. }
  49. @GetMapping("/implicit")
  50. String implicit(Model model) {
  51. // @formatter:off
  52. Mono<String> body = this.webClient
  53. .get()
  54. .retrieve()
  55. .bodyToMono(String.class);
  56. // @formatter:on
  57. model.addAttribute("body", body);
  58. return "response";
  59. }
  60. }