转载

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

温馨提示:
本文最后更新于 2021年08月13日,已超过 1,078 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

本文转载自:https://xkcoding.com/2019/05/22/spring-boot-login-with-oauth.html

前言

此 demo 主要演示 Spring Boot 项目如何使用 史上最全的第三方登录工具 - JustAuth 实现第三方登录。
如果技术选型是 JFinal 的,请查看此 demo
https://github.com/xkcoding/jfinal-justauth-demo
JustAuth,如你所见,它仅仅是一个第三方授权登录工具类库,它可以让我们脱离繁琐的第三方登录SDK,让登录变得So easy!

  1. :已集成十多家第三方平台(国内外常用的基本都已包含),后续依然还有扩展计划!
  2. :API就是奔着最简单去设计的(见后面快速开始),尽量让您用起来没有障碍感!
    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
  • 2.解压安装包
$ tar -zxvf frp_0.27.0_linux_amd64.tar.gz
  • 3.修改配置文件
$ cd frp_0.27.0_linux_amd64
$ vim frps.ini

[common]                                                                                                                  
bind_port = 7100                                                                                                          
vhost_http_port = 7200
  • 4.启动frp服务端
$ ./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
  • 2.解压安装包
$ tar -zxvf frp_0.27.0_darwin_amd64.tar.gz
  • 3.修改配置文件,配置服务端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
  • 4.启动frp客户端
$ ./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 的搭建就不在此赘述了,只说配置

server {
    listen       80;
    server_name  oauth.xkcoding.com;         

    location / {
        proxy_pass http://127.0.0.1:7200;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header   X-Real-IP        $remote_addr;                                                                 
        proxy_buffering off;                                                                                              
        sendfile off;                                                                                                     
        proxy_max_temp_file_size 0;                                                                                       
        client_max_body_size       10m;                                                                                   
        client_body_buffer_size    128k;                                                                                  
        proxy_connect_timeout      90;                                                                                    
        proxy_send_timeout         90;                                                                                    
        proxy_read_timeout         90;                                                                                    
        proxy_temp_file_write_size 64k;                                                                                   
        proxy_http_version 1.1;                                                                                           
        proxy_request_buffering off; 
    }
}

测试配置文件是否有问题

$ 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 微信开放平台申请

这里微信开放平台需要用企业的,个人没有资质,所以我在某宝租了一个月的资质,需要的可以进这儿http://t.cn/AilxgTx1

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

  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

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>spring-boot-demo-social</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>spring-boot-demo-social</name>
  <description>Demo project for Spring Boot</description>

  <parent>
    <groupId>com.xkcoding</groupId>
    <artifactId>spring-boot-demo</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring.social.version>1.1.6.RELEASE</spring.social.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- oauth工具类 -->
    <dependency>
      <groupId>me.zhyd.oauth</groupId>
      <artifactId>JustAuth</artifactId>
      <version>1.8.1</version>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>

    <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
    </dependency>
  </dependencies>

  <build>
    <finalName>spring-boot-demo-social</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

2.2. application.yml

server:
  port: 8080
  servlet:
    context-path: /demo

oauth:
  qq:
    client-id: 1015*****
    client-secret: 1f7d08df55766**************
    redirect-uri: http://oauth.xkcoding.com/demo/oauth/qq/callback
  github:
    client-id: 2d25a70**************
    client-secret: 5a2919b5fe911567343**************
    redirect-uri: http://oauth.xkcoding.com/demo/oauth/github/callback
  wechat:
    client-id: wxdcb31**************
    client-secret: b4e9dc6841ef7d**************
    redirect-uri: http://oauth.xkcoding.com/demo/oauth/wechat/callback
  google:
    client-id: 716518501517-6dbdkapivhia806vqcjjh9nttj3**************
    client-secret: 9IBornd7w1A**************
    redirect-uri: http://oauth.xkcoding.com/demo/oauth/google/callback
  microsoft:
    client-id: 7bdce818-2c8e-4b**************
    client-secret: Iu0zZ43RQydo_FkD**************
    redirect-uri: https://oauth.xkcoding.com/demo/oauth/microsoft/callback
  mi:
    client-id: 2882303**************
    client-secret: nFeTt89Yn**************
    redirect-uri: http://oauth.xkcoding.com/demo/oauth/mi/callback

2.3. OAuthProperties.java

/**
 * <p>
 * 第三方登录配置
 * </p>
 *
 * @package: com.xkcoding.oauth.config.props
 * @description: 第三方登录配置
 * @author: yangkai.shen
 * @date: Created in 2019-05-17 15:33
 * @copyright: Copyright (c) 2019
 * @version: V1.0
 * @modified: yangkai.shen
 */
@Data
@Component
@ConfigurationProperties(prefix = "oauth")
public class OAuthProperties {
    /**
     * QQ 配置
     */
    private AuthConfig qq;

    /**
     * github 配置
     */
    private AuthConfig github;

    /**
     * 微信 配置
     */
    private AuthConfig wechat;

    /**
     * Google 配置
     */
    private AuthConfig google;

    /**
     * Microsoft 配置
     */
    private AuthConfig microsoft;

    /**
     * Mi 配置
     */
    private AuthConfig mi;
}

2.4. OauthController.java

/**
 * <p>
 * 第三方登录 Controller
 * </p>
 *
 * @package: com.xkcoding.oauth.controller
 * @description: 第三方登录 Controller
 * @author: yangkai.shen
 * @date: Created in 2019-05-17 10:07
 * @copyright: Copyright (c) 2019
 * @version: V1.0
 * @modified: yangkai.shen
 */
@RestController
@RequestMapping("/oauth")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class OauthController {
    private final OAuthProperties properties;

    /**
     * 登录类型
     */
    @GetMapping
    public Dict loginType() {
        return Dict.create()
                .set("QQ登录", "http://oauth.xkcoding.com/demo/oauth/login/qq")
                .set("GitHub登录", "http://oauth.xkcoding.com/demo/oauth/login/github")
                .set("微信登录", "http://oauth.xkcoding.com/demo/oauth/login/wechat")
                .set("Google登录", "http://oauth.xkcoding.com/demo/oauth/login/google")
                .set("Microsoft 登录", "http://oauth.xkcoding.com/demo/oauth/login/microsoft")
                .set("小米登录", "http://oauth.xkcoding.com/demo/oauth/login/mi");
    }

    /**
     * 登录
     *
     * @param oauthType 第三方登录类型
     * @param response  response
     * @throws IOException
     */
    @RequestMapping("/login/{oauthType}")
    public void renderAuth(@PathVariable String oauthType, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest(oauthType);
        response.sendRedirect(authRequest.authorize());
    }

    /**
     * 登录成功后的回调
     *
     * @param oauthType 第三方登录类型
     * @param callback  携带返回的信息
     * @return 登录成功后的信息
     */
    @RequestMapping("/{oauthType}/callback")
    public AuthResponse login(@PathVariable String oauthType, AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest(oauthType);
        AuthResponse response = authRequest.login(callback);
        // 移除校验通过的state
        AuthState.delete(oauthType);
        return response;
    }

    private AuthRequest getAuthRequest(String oauthType) {
        AuthSource authSource = AuthSource.valueOf(oauthType.toUpperCase());
        String state = AuthState.create(oauthType);
        switch (authSource) {
            case QQ:
                return getQqAuthRequest(state);
            case GITHUB:
                return getGithubAuthRequest(state);
            case WECHAT:
                return getWechatAuthRequest(state);
            case GOOGLE:
                return getGoogleAuthRequest(state);
            case MICROSOFT:
                return getMicrosoftAuthRequest(state);
            case MI:
                return getMiAuthRequest(state);
            default:
                throw new RuntimeException("暂不支持的第三方登录");
        }
    }

    private AuthRequest getQqAuthRequest(String state) {
        AuthConfig authConfig = properties.getQq();
        authConfig.setState(state);
        return new AuthQqRequest(authConfig);
    }

    private AuthRequest getGithubAuthRequest(String state) {
        AuthConfig authConfig = properties.getGithub();
        authConfig.setState(state);
        return new AuthGithubRequest(authConfig);
    }

    private AuthRequest getWechatAuthRequest(String state) {
        AuthConfig authConfig = properties.getWechat();
        authConfig.setState(state);
        return new AuthWeChatRequest(authConfig);
    }

    private AuthRequest getGoogleAuthRequest(String state) {
        AuthConfig authConfig = properties.getGoogle();
        authConfig.setState(state);
        return new AuthGoogleRequest(authConfig);
    }

    private AuthRequest getMicrosoftAuthRequest(String state) {
        AuthConfig authConfig = properties.getMicrosoft();
        authConfig.setState(state);
        return new AuthMicrosoftRequest(authConfig);
    }

    private AuthRequest getMiAuthRequest(String state) {
        AuthConfig authConfig = properties.getMi();
        authConfig.setState(state);
        return new AuthMiRequest(authConfig);
    }
}

3. 运行方式

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

Google 登录,有可能因为祖国的强大导致测试失败,自行解决~ :kissing_smiling_eyes:

image-20190617154343815


参考

  1. JustAuth 项目地址:https://github.com/zhangyd-c/JustAuth
  2. frp内网穿透项目地址:https://github.com/fatedier/frp
  3. frp内网穿透官方中文文档:https://github.com/fatedier/frp/blob/master/README_zh.md
  4. Frp实现内网穿透:https://zhuanlan.zhihu.com/p/45445979
  5. QQ互联文档:http://wiki.connect.qq.com/%E5%87%86%E5%A4%87%E5%B7%A5%E4%BD%9C_oauth2-0
  6. 微信开放平台文档:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN
  7. GitHub第三方登录文档:https://developer.github.com/apps/building-oauth-apps/
  8. 谷歌Oauth2文档:https://developers.google.com/identity/protocols/OpenIDConnect
  9. 微软Oauth2文档:https://docs.microsoft.com/zh-cn/graph/auth-v2-user
  10. 小米开放平台账号服务文档:https://dev.mi.com/console/doc/detail?pId=707
正文到此结束
本文目录