效果展示

guns-sso.mp4 (7.76MB)

版本说明

  • pig 2.10
  • guns vip 1.0

pig 客户端表

  1. INSERT INTO `pig`.`sys_oauth_client_details`(`client_id`, `resource_ids`, `client_secret`, `scope`, `authorized_grant_types`, `web_server_redirect_uri`, `authorities`, `access_token_validity`, `refresh_token_validity`, `additional_information`, `autoapprove`) VALUES ('guns', NULL, 'guns', 'server', 'refresh_token,authorization_code', 'http://localhost:8087/sso/code', NULL, 43200, 2592001, NULL, 'true');

调整 WebSecurityConfig

image.png

新增SSO 登录接口

  • LoginController 新增如下端点, 代码中的URL 根据实际地址修改即可

注意:授权码模式下回调地址不能使用localhost,可以使用127.0.0.1

  1. @SneakyThrows
  2. @RequestMapping(value = "/sso/login", method = RequestMethod.GET)
  3. public RedirectView loginSso(HttpServletRequest request, HttpServletResponse response) {
  4. String url = String.format("%s?response_type=code&scope=%s&client_id=%s&state=%s&redirect_uri=%s",
  5. "http://localhost:3000/oauth/authorize",
  6. "server",
  7. "guns",
  8. "guns",
  9. URLEncoder.encode("http://127.0.0.1:8087/sso/code", "UTF-8"));
  10. return new RedirectView(url);
  11. }
  12. @SneakyThrows
  13. @ResponseBody
  14. @RequestMapping(value = "/sso/code", method = RequestMethod.GET)
  15. public RedirectView loginCode(HttpServletRequest request, HttpServletResponse response) {
  16. String code = super.getPara("code");
  17. String template = "http://localhost:3000/oauth/token?grant_type=authorization_code&scope=%s&code=%s&redirect_uri=%s";
  18. final String url = String.format(template, "server", code, URLEncoder.encode(request.getRequestURL().toString(), "UTF-8"));
  19. String body = HttpRequest.get(url)
  20. .basicAuth("guns", "guns")
  21. .execute()
  22. .body();
  23. JSONObject parse = JSONUtil.parseObj(body);
  24. String username = parse.getStr("username");
  25. //登录并创建token
  26. String token = authService.login(username);
  27. return new RedirectView("/");
  28. }

前端使用

  1. http://localhost:8087/sso/login

退出修改

  • LoginController.java
    1. @RequestMapping(value = "/logout")
    2. @ResponseBody
    3. public void logOut(HttpServletResponse response) {
    4. authService.logout();
    5. response.sendRedirect("http://localhost:3000/logout?redirect_url="+ URLEncoder.encode("http://localhost:8087"));
    6. }

    ❤ 问题咨询

    手势点击蓝字求关注简约风动态引导关注__2022-09-07+23_18_38.gif