GithubOauth.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.nosum.common.constant;
  2. import cn.hutool.http.Header;
  3. import cn.hutool.http.HttpRequest;
  4. import com.nosum.common.util.HttpClientUtils;
  5. import com.nosum.common.util.JsonUtil;
  6. import com.nosum.deliver.auth.domain.vo.AuthUserVO;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. import java.util.Optional;
  10. public class GithubOauth {
  11. private static final String CLIENT_ID = "62315a189a3efded767b";
  12. private static final String CLIENT_SECRET = "c0348e4697552e1dcce200d43ab21984bf2e9973";
  13. private static final String AUTH_URL = "https://github.com/login/oauth/authorize";
  14. private static final String TOKEN_URL = "https://github.com/login/oauth/access_token";
  15. private static final String USER_INFO_URL = "https://api.github.com/user";
  16. public static String getAuthUrl() {
  17. return AUTH_URL + "?state=c2NvcGU9bm9zdW1ibG9n&client_id=" + CLIENT_ID;
  18. }
  19. public static String getAccessToken(String code) {
  20. Map<String, Object> params = new HashMap<>();
  21. params.put("code", code);
  22. params.put("client_id", CLIENT_ID);
  23. params.put("client_secret", CLIENT_SECRET);
  24. HttpRequest post = HttpRequest.post(TOKEN_URL);
  25. post.body(JsonUtil.toJsonString(params)).contentType("application/json").header(Header.ACCEPT, "application/json");
  26. return post.execute().body();
  27. }
  28. public static String getHtml(Object result) {
  29. // vue前端获取这个数据,去登录。
  30. return "<head><meta charset=\"UTF-8\"></head>" +
  31. "<body><p style=\"text-align: center;\"><h3>欢迎访问青涩知夏博客,登录中,请稍后......</h3></p></body>" +
  32. "\n <script type=\"text/javascript\">\n" +
  33. " window.onload=function () {\n" +
  34. " var message =" + JsonUtil.toJsonString(result) + ";\n" +
  35. " window.opener.parent.postMessage(message, '*');\n" +
  36. " parent.window.close();\n" +
  37. " }</script>";
  38. }
  39. public static String getErrorHtml() {
  40. return getHtml("error");
  41. }
  42. public static AuthUserVO getUserInfo(String code) {
  43. Optional<String> optional = Optional.ofNullable(code);
  44. if (optional.isPresent()) {
  45. Map<String, String> accessTokenMap = JsonUtil.parseHashMap(getAccessToken(optional.get()));
  46. String userinfo_url = USER_INFO_URL + "?access_token=" + accessTokenMap.get("access_token"); //通过token获得用户信息
  47. Map<String, String> resultMap = JsonUtil.parseHashMap(HttpClientUtils.doGet(userinfo_url));
  48. AuthUserVO authUserVO = new AuthUserVO();
  49. authUserVO.setSocialId(String.valueOf(resultMap.get("id")));
  50. authUserVO.setAvatar(resultMap.get("avatar_url"));
  51. authUserVO.setName(resultMap.get("login"));
  52. return authUserVO;
  53. }
  54. return null;
  55. }
  56. }