OauthController.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package com.boman.auth.controller;
  2. import cn.hutool.core.util.StrUtil;
  3. import com.alibaba.fastjson.JSON;
  4. import com.boman.common.core.utils.JSONArrayUtils;
  5. import com.boman.common.core.utils.StringUtils;
  6. import com.fasterxml.jackson.annotation.JsonFormat;
  7. import com.xkcoding.justauth.AuthRequestFactory;
  8. import io.micrometer.core.instrument.util.JsonUtils;
  9. import lombok.RequiredArgsConstructor;
  10. import lombok.extern.slf4j.Slf4j;
  11. import me.zhyd.oauth.config.AuthSource;
  12. import me.zhyd.oauth.model.AuthCallback;
  13. import me.zhyd.oauth.model.AuthResponse;
  14. import me.zhyd.oauth.request.AuthRequest;
  15. import me.zhyd.oauth.utils.AuthStateUtils;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.web.bind.annotation.GetMapping;
  18. import org.springframework.web.bind.annotation.PathVariable;
  19. import org.springframework.web.bind.annotation.RequestMapping;
  20. import org.springframework.web.bind.annotation.RestController;
  21. import javax.servlet.http.HttpServletResponse;
  22. import java.io.IOException;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.stream.Collectors;
  26. /**
  27. * @author tjf
  28. * @Date: 2021/05/24/11:41
  29. */
  30. @Slf4j
  31. @RestController
  32. @RequestMapping("/oauth")
  33. @RequiredArgsConstructor(onConstructor_ = @Autowired)
  34. public class OauthController {
  35. private final AuthRequestFactory factory;
  36. @GetMapping
  37. public List<String> list() {
  38. return factory.oauthList();
  39. }
  40. @GetMapping("/login/{type}")
  41. public void login(@PathVariable String type, HttpServletResponse response) throws IOException {
  42. AuthRequest authRequest = factory.get(type);
  43. //生成授权地址,并重定向
  44. String authorize = authRequest.authorize(type + "::" + AuthStateUtils.createState());
  45. response.sendRedirect(authorize);
  46. }
  47. /**
  48. * 回调登录
  49. * @param type
  50. * @param callback
  51. * @return
  52. */
  53. @RequestMapping("/{type}/callback")
  54. public AuthResponse login(@PathVariable String type, AuthCallback callback) {
  55. AuthRequest authRequest = factory.get(getAuthSource(type));
  56. AuthResponse response = authRequest.login(callback);
  57. log.info("【response】= {}", JSON.toJSONString(response));
  58. return response;
  59. }
  60. private String getAuthSource(String type) {
  61. if (StrUtil.isNotBlank(type)) {
  62. return type.toUpperCase();
  63. } else {
  64. throw new RuntimeException("类型为空");
  65. }
  66. }
  67. }