2021-05-10学习笔记 第三方登录

Spring Boot 快速集成第三方登录功能

weixin_41249041 2019-07-21 22:29:13  2514  收藏 11

分类专栏: Springboot java

前言

https://xkcoding.com/2019/05/22/spring-boot-login-with-oauth.html

此 demo 主要演示 Spring Boot 项目如何使用 史上最全的第三方登录工具 - JustAuth(https://github.com/zhangyd-c/JustAuth 实现第三方登录。

如果技术选型是 JFinal 的,请查看此 demo(https://github.com/xkcoding/jfinal-justauth-demo

https://github.com/xkcoding/jfinal-justauth-demo

JustAuth,如你所见,它仅仅是一个第三方授权登录工具类库,它可以让我们脱离繁琐的第三方登录 SDK,让登录变得So easy!

  1. :已集成十多家第三方平台(国内外常用的基本都已包含),后续依然还有扩展计划!
  2. :API 就是奔着最简单去设计的(见后面快速开始),尽量让您用起来没有障碍感!(https://github.com/zhangyd-c/JustAuth#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B

PS: 本人十分幸运的参与到了这个 SDK 的开发,主要开发了 QQ 登录、微信登录、小米登录、微软登录、谷歌登录这 5 个第三方登录,以及一些 BUG 的修复工作。再次感谢 @母狼 开源这个又好用又全面的第三方登录 SDK。

1. 环境准备

1.1. 公网服务器准备

首先准备一台有公网 IP 的服务器,可以选用阿里云或者腾讯云,如果选用的是阿里云的,可以使用我的优惠链接购买。

1.2. 内网穿透 frp 搭建

frp 安装程序:https://github.com/fatedier/frp/releases

1.2.1. frp 服务端搭建

服务端搭建在上一步准备的公网服务器上,因为服务器是 centos7 x64 的系统,因此,这里下载安装包版本为 linux_amd64 的 frp_0.27.0_linux_amd64.tar.gz 。

  1. 下载安装包

$ wget https://github.com/fatedier/frp/releases/download/v0.27.0/frp_0.27.0_linux_amd64.tar.gz

解压安装包

$ tar -zxvf frp_0.27.0_linux_amd64.tar.gz

修改配置文件

$ cd frp_0.27.0_linux_amd64
$ vim frps.ini

[common]                                                                                                                  
bind_port = 7100                                                                                                          
vhost_http_port = 7200

启动 frp 服务端

1
2
3
4
$ ./frps -c frps.ini
2019/06/15 16:42:02 [I] [service.go:139] frps tcp listen on 0.0.0.0:7100
2019/06/15 16:42:02 [I] [service.go:181] http service listen on 0.0.0.0:7200
2019/06/15 16:42:02 [I] [root.go:204] Start frps success

1.2.2. frp 客户端搭建

客户端搭建在本地的 Mac 上,因此下载安装包版本为 darwin_amd64 的 frp_0.27.0_darwin_amd64.tar.gz 。

  1. 下载安装包

$ wget https://github.com/fatedier/frp/releases/download/v0.27.0/frp_0.27.0_darwin_amd64.tar.gz

解压安装包

$ tar -zxvf frp_0.27.0_darwin_amd64.tar.gz

修改配置文件,配置服务端 ip 端口及监听的域名信息

$ cd frp_0.27.0_darwin_amd64
$ vim frpc.ini

[common]
server_addr = 120.92.169.103
server_port = 7100

[web]
type = http
local_port = 8080
custom_domains = oauth.xkcoding.com

启动 frp 客户端

1
2
3
4
$ ./frpc -c frpc.ini
2019/06/15 16:48:52 [I] [service.go:221] login to server success, get run id [8bb83bae5c58afe6], server udp port [0]
2019/06/15 16:48:52 [I] [proxy_manager.go:137] [8bb83bae5c58afe6] proxy added: [web]
2019/06/15 16:48:52 [I] [control.go:144] [web] start proxy success

1.3. 配置域名解析

前往阿里云 DNS 解析,将域名解析到我们的公网服务器上,比如我的就是将 oauth.xkcoding.com -> 120.92.169.103

image-20190615165843639

1.4. nginx 代理

nginx 的搭建就不在此赘述了,只说配置

 
  1.  
  2. server {

  3. listen 80;

  4. server_name oauth.xkcoding.com;

  5.  
  6. location / {

  7. proxy_pass http://127.0.0.1:7200;

  8. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

  9. proxy_set_header Host $http_host;

  10. proxy_set_header X-Forwarded-Proto $scheme;

  11. proxy_set_header X-Real-IP $remote_addr;

  12. proxy_buffering off;

  13. sendfile off;

  14. proxy_max_temp_file_size 0;

  15. client_max_body_size 10m;

  16. client_body_buffer_size 128k;

  17. proxy_connect_timeout 90;

  18. proxy_send_timeout 90;

  19. proxy_read_timeout 90;

  20. proxy_temp_file_write_size 64k;

  21. proxy_http_version 1.1;

  22. proxy_request_buffering off;

  23. }

  24. }

测试配置文件是否有问题

$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

重新加载配置文件,使其生效

$ nginx -s reload

现在当我们在浏览器输入 oauth.xkcoding.com 的时候,网络流量其实会经历以下几个步骤:

  1. 通过之前配的 DNS 域名解析会访问到我们的公网服务器 120.92.169.103 的 80 端口
  2. 再经过 nginx,代理到本地的 7200 端口
  3. 再经过 frp 穿透到我们的 Mac 电脑的 8080 端口
  4. 此时 8080 就是我们的应用程序端口

1.5. 第三方平台申请

1.5.1. QQ 互联平台申请

  1. 前往 https://connect.qq.com/

  2. 申请开发者

  3. 应用管理 -> 添加网站应用,等待审核通过即可

    image-20190617144655429

1.5.2. GitHub 平台申请

  1. 前往 https://github.com/settings/developers

  2. 点击 New OAuth App 按钮创建应用

    image-20190617145839851

1.5.3 微信开放平台申请

这里微信开放平台需要用企业的,个人没有资质,所以我在某宝租了一个月的资质,需要的可以 戳我租赁

声明:本人与该店铺无利益相关,纯属个人觉得好用做分享

该店铺有两种方式:

  1. 店铺支持帮你过企业资质,这里就用你自己的开放平台号就好了
  2. 临时使用可以问店家租一个月进行开发,这里租了之后,店家会把 AppID 和 AppSecret 的信息发给你,你提供回调域就好了

因此这里我就贴出一张授权回调的地址作参考。

image-20190617153552218

1.5.4. 谷歌开放平台申请

  1. 前往 https://console.developers.google.com/projectcreate 创建项目

  2. 前往 https://console.developers.google.com/apis/credentials ,在第一步创建的项目下,添加应用

    image-20190617151119584

    image-20190617150903039

1.5.5. 微软开放平台申请

  1. 前往 https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade 注册应用

  2. 在注册应用的时候就需要填写回调地址,当然后期也可以重新修改

    image-20190617152529449

  3. client id 在这里

    image-20190617152805581

  4. client secret 需要自己在这里生成

    image-20190617152711938

1.5.6. 小米开放平台申请

  1. 申请小米开发者,审核通过

  2. 前往 https://dev.mi.com/passport/oauth2/applist 添加 oauth 应用,选择 创建网页应用

  3. 填写基本信息之后,进入应用信息页面填写 回调地址

    image-20190617151502414

  4. 应用审核通过之后,可以在应用信息页面的 应用详情 查看到 AppKey 和 AppSecret,吐槽下,小米应用的审核速度特别慢,需要耐心等待。。。。

    image-20190617151624603


2. 主要代码

代码地址:https://github.com/xkcoding/spring-boot-demo/tree/master/spring-boot-demo-social

2.1. pom.xml

 
  1.  
  2. <?xml version="1.0" encoding="UTF-8"?>

  3. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  5. <modelVersion>4.0.0</modelVersion>

  6.  
  7. <artifactId>spring-boot-demo-social</artifactId>

  8. <version>1.0.0-SNAPSHOT</version>

  9. <packaging>jar</packaging>

  10.  
  11. <name>spring-boot-demo-social</name>

  12. <description>Demo project for Spring Boot</description>

  13.  
  14. <parent>

  15. <groupId>com.xkcoding</groupId>

  16. <artifactId>spring-boot-demo</artifactId>

  17. <version>1.0.0-SNAPSHOT</version>

  18. </parent>

  19.  
  20. <properties>

  21. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  22. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

  23. <java.version>1.8</java.version>

  24. <spring.social.version>1.1.6.RELEASE</spring.social.version>

  25. </properties>

  26.  
  27. <dependencies>

  28. <dependency>

  29. <groupId>org.springframework.boot</groupId>

  30. <artifactId>spring-boot-starter-web</artifactId>

  31. </dependency>

  32.  
  33. <dependency>

  34. <groupId>org.springframework.boot</groupId>

  35. <artifactId>spring-boot-starter-test</artifactId>

  36. <scope>test</scope>

  37. </dependency>

  38.  
  39. <!-- oauth工具类 -->

  40. <dependency>

  41. <groupId>me.zhyd.oauth</groupId>

  42. <artifactId>JustAuth</artifactId>

  43. <version>1.8.1</version>

  44. </dependency>

  45.  
  46. <dependency>

  47. <groupId>org.projectlombok</groupId>

  48. <artifactId>lombok</artifactId>

  49. <optional>true</optional>

  50. </dependency>

  51.  
  52. <dependency>

  53. <groupId>com.google.guava</groupId>

  54. <artifactId>guava</artifactId>

  55. </dependency>

  56.  
  57. <dependency>

  58. <groupId>cn.hutool</groupId>

  59. <artifactId>hutool-all</artifactId>

  60. </dependency>

  61. </dependencies>

  62.  
  63. <build>

  64. <finalName>spring-boot-demo-social</finalName>

  65. <plugins>

  66. <plugin>

  67. <groupId>org.springframework.boot</groupId>

  68. <artifactId>spring-boot-maven-plugin</artifactId>

  69. </plugin>

  70. </plugins>

  71. </build>

  72.  
  73. </project>

2.2. application.yml

 
  1.  
  2. server:

  3. port: 8080

  4. servlet:

  5. context-path: /demo

  6.  
  7. oauth:

  8. qq:

  9. client-id: 1015*****

  10. client-secret: 1f7d08df55766**************

  11. redirect-uri: http://oauth.xkcoding.com/demo/oauth/qq/callback

  12. github:

  13. client-id: 2d25a70**************

  14. client-secret: 5a2919b5fe911567343**************

  15. redirect-uri: http://oauth.xkcoding.com/demo/oauth/github/callback

  16. wechat:

  17. client-id: wxdcb31**************

  18. client-secret: b4e9dc6841ef7d**************

  19. redirect-uri: http://oauth.xkcoding.com/demo/oauth/wechat/callback

  20. google:

  21. client-id: 716518501517-6dbdkapivhia806vqcjjh9nttj3**************

  22. client-secret: 9IBornd7w1A**************

  23. redirect-uri: http://oauth.xkcoding.com/demo/oauth/google/callback

  24. microsoft:

  25. client-id: 7bdce818-2c8e-4b**************

  26. client-secret: Iu0zZ43RQydo_FkD**************

  27. redirect-uri: https://oauth.xkcoding.com/demo/oauth/microsoft/callback

  28. mi:

  29. client-id: 2882303**************

  30. client-secret: nFeTt89Yn**************

  31. redirect-uri: http://oauth.xkcoding.com/demo/oauth/mi/callback

2.3. OAuthProperties.java

 
  1.  
  2. /**

  3. * <p>

  4. * 第三方登录配置

  5. * </p>

  6. *

  7. * @package: com.xkcoding.oauth.config.props

  8. * @description: 第三方登录配置

  9. * @author: yangkai.shen

  10. * @date: Created in 2019-05-17 15:33

  11. * @copyright: Copyright (c) 2019

  12. * @version: V1.0

  13. * @modified: yangkai.shen

  14. */

  15. @Data

  16. @Component

  17. @ConfigurationProperties(prefix = "oauth")

  18. public class OAuthProperties {

  19. /**

  20. * QQ 配置

  21. */

  22. private AuthConfig qq;

  23.  
  24. /**

  25. * github 配置

  26. */

  27. private AuthConfig github;

  28.  
  29. /**

  30. * 微信 配置

  31. */

  32. private AuthConfig wechat;

  33.  
  34. /**

  35. * Google 配置

  36. */

  37. private AuthConfig google;

  38.  
  39. /**

  40. * Microsoft 配置

  41. */

  42. private AuthConfig microsoft;

  43.  
  44. /**

  45. * Mi 配置

  46. */

  47. private AuthConfig mi;

  48. }

2.4. OauthController.java

 
  1.  
  2. /**

  3. * <p>

  4. * 第三方登录 Controller

  5. * </p>

  6. *

  7. * @package: com.xkcoding.oauth.controller

  8. * @description: 第三方登录 Controller

  9. * @author: yangkai.shen

  10. * @date: Created in 2019-05-17 10:07

  11. * @copyright: Copyright (c) 2019

  12. * @version: V1.0

  13. * @modified: yangkai.shen

  14. */

  15. @RestController

  16. @RequestMapping("/oauth")

  17. @RequiredArgsConstructor(onConstructor_ = @Autowired)

  18. public class OauthController {

  19. private final OAuthProperties properties;

  20.  
  21. /**

  22. * 登录类型

  23. */

  24. @GetMapping

  25. public Dict loginType() {

  26. return Dict.create()

  27. .set("QQ登录", "http://oauth.xkcoding.com/demo/oauth/login/qq")

  28. .set("GitHub登录", "http://oauth.xkcoding.com/demo/oauth/login/github")

  29. .set("微信登录", "http://oauth.xkcoding.com/demo/oauth/login/wechat")

  30. .set("Google登录", "http://oauth.xkcoding.com/demo/oauth/login/google")

  31. .set("Microsoft 登录", "http://oauth.xkcoding.com/demo/oauth/login/microsoft")

  32. .set("小米登录", "http://oauth.xkcoding.com/demo/oauth/login/mi");

  33. }

  34.  
  35. /**

  36. * 登录

  37. *

  38. * @param oauthType 第三方登录类型

  39. * @param response response

  40. * @throws IOException

  41. */

  42. @RequestMapping("/login/{oauthType}")

  43. public void renderAuth(@PathVariable String oauthType, HttpServletResponse response) throws IOException {

  44. AuthRequest authRequest = getAuthRequest(oauthType);

  45. response.sendRedirect(authRequest.authorize());

  46. }

  47.  
  48. /**

  49. * 登录成功后的回调

  50. *

  51. * @param oauthType 第三方登录类型

  52. * @param callback 携带返回的信息

  53. * @return 登录成功后的信息

  54. */

  55. @RequestMapping("/{oauthType}/callback")

  56. public AuthResponse login(@PathVariable String oauthType, AuthCallback callback) {

  57. AuthRequest authRequest = getAuthRequest(oauthType);

  58. AuthResponse response = authRequest.login(callback);

  59. // 移除校验通过的state

  60. AuthState.delete(oauthType);

  61. return response;

  62. }

  63.  
  64. private AuthRequest getAuthRequest(String oauthType) {

  65. AuthSource authSource = AuthSource.valueOf(oauthType.toUpperCase());

  66. String state = AuthState.create(oauthType);

  67. switch (authSource) {

  68. case QQ:

  69. return getQqAuthRequest(state);

  70. case GITHUB:

  71. return getGithubAuthRequest(state);

  72. case WECHAT:

  73. return getWechatAuthRequest(state);

  74. case GOOGLE:

  75. return getGoogleAuthRequest(state);

  76. case MICROSOFT:

  77. return getMicrosoftAuthRequest(state);

  78. case MI:

  79. return getMiAuthRequest(state);

  80. default:

  81. throw new RuntimeException("暂不支持的第三方登录");

  82. }

  83. }

  84.  
  85. private AuthRequest getQqAuthRequest(String state) {

  86. AuthConfig authConfig = properties.getQq();

  87. authConfig.setState(state);

  88. return new AuthQqRequest(authConfig);

  89. }

  90.  
  91. private AuthRequest getGithubAuthRequest(String state) {

  92. AuthConfig authConfig = properties.getGithub();

  93. authConfig.setState(state);

  94. return new AuthGithubRequest(authConfig);

  95. }

  96.  
  97. private AuthRequest getWechatAuthRequest(String state) {

  98. AuthConfig authConfig = properties.getWechat();

  99. authConfig.setState(state);

  100. return new AuthWeChatRequest(authConfig);

  101. }

  102.  
  103. private AuthRequest getGoogleAuthRequest(String state) {

  104. AuthConfig authConfig = properties.getGoogle();

  105. authConfig.setState(state);

  106. return new AuthGoogleRequest(authConfig);

  107. }

  108.  
  109. private AuthRequest getMicrosoftAuthRequest(String state) {

  110. AuthConfig authConfig = properties.getMicrosoft();

  111. authConfig.setState(state);

  112. return new AuthMicrosoftRequest(authConfig);

  113. }

  114.  
  115. private AuthRequest getMiAuthRequest(String state) {

  116. AuthConfig authConfig = properties.getMi();

  117. authConfig.setState(state);

  118. return new AuthMiRequest(authConfig);

  119. }

  120. }

3. 运行方式

打开浏览器,输入 http://oauth.xkcoding.com/demo/oauth ,点击各个登录方式自行测试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值