5.12 VUE项目实现Google 第三方登录

目录

一、Google开发者平台配置

Google Cloud: https://console.cloud.google.com/

1. 新建项目

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


2. 配置 OAuth 权限请求页面并选择范围

首次使用谷歌开发平台时需要配置,配置过的可以跳过此步骤。

参考文章: 配置 OAuth 权限请求页面并选择范围

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述
在这里插入图片描述


3. 启动API 和 服务

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述

在这里插入图片描述


Client_ID 在之后代码中会用到,不用提前保存,需要了就点一下这个页面的复制按钮


在这里插入图片描述


二、 登录代码实现

1. 参考Google官网文档

显示“使用 Google 帐号登录”按钮

在这里插入图片描述

请务必在用户可能登录的任何页面上加载客户端库。

<script src="https://accounts.google.com/gsi/client" async></script>

使用 HTML 呈现登录按钮,并将 JWT 返回到平台的登录端点。

<html>
  <body>
    <script src="https://accounts.google.com/gsi/client" async></script>
    <div id="g_id_onload"
        data-client_id="YOUR_GOOGLE_CLIENT_ID"
        data-login_uri="https://your.domain/your_login_endpoint"
        data-auto_prompt="false">
    </div>
    <div class="g_id_signin"
        data-type="standard"
        data-size="large"
        data-theme="outline"
        data-text="sign_in_with"
        data-shape="rectangular"
        data-logo_alignment="left">
    </div>
  <body>
</html>

使用 JavaScript 呈现登录按钮,并将 JWT 返回给浏览器的 JavaScript 回调处理程序。

<html>
  <body>
    <script src="https://accounts.google.com/gsi/client" async></script>
    <script>
      function handleCredentialResponse(response) {
        console.log("Encoded JWT ID token: " + response.credential);
      }
      window.onload = function () {
        google.accounts.id.initialize({
          client_id: "YOUR_GOOGLE_CLIENT_ID"
          callback: handleCredentialResponse
        });
        google.accounts.id.renderButton(
          document.getElementById("buttonDiv"),
          { theme: "outline", size: "large" }  // customization attributes
        );
        google.accounts.id.prompt(); // also display the One Tap dialog
      }
    </script>
    <div id="buttonDiv"></div>
  </body>
</html>

2. Google官网代码生成器

生成HTML代码: https://developers.google.com/identity/gsi/web/tools/configurator?hl=zh-cn


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


<div id="g_id_onload"
     data-client_id="xxxx"
     data-context="signin"
     data-ux_mode="popup"
     data-login_uri="http://localhost:9011"
     data-auto_prompt="false">
</div>

<div class="g_id_signin"
     data-type="standard"
     data-shape="rectangular"
     data-theme="filled_blue"
     data-text="signin_with"
     data-size="large"
     data-logo_alignment="left">
</div>

3. 项目中实装


在这里插入图片描述


        <v-row>
          <v-col>
            <div class="g-signin-button" style="height: 50px; width: 30%">
              <component
                :is="'script'"
                src="https://accounts.google.com/gsi/client"
                ansyc
              />
              <div
                id="g_id_onload"
                data-client_id="换成你自己的Client_ID.apps.googleusercontent.com"
                data-context="signin"
                data-ux_mode="popup"
                data-callback="googleSignCallBack"
                data-auto_prompt="false"
              ></div>
              <div
                class="g_id_signin"
                data-type="standard"
                data-shape="rectangular"
                data-theme="filled_blue"
                data-text="signin_with"
                data-size="large"
                data-locale="ja"
                data-logo_alignment="left"
              ></div>
            </div>
          </v-col>
        </v-row>

在这里插入图片描述


  mounted: function () {
    window.googleSignCallBack = this.googleSignCallBack;
  },

  methods: {
    googleSignCallBack(googleUser) {
      console.log("googleUser", googleUser);
    },
  },

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
实现第三方qq登录,可以使用QQ互联提供的开放平台接口。具体的步骤如下: 1. 注册成为QQ互联开发者,并创建应用。在创建应用时,需要填写应用的基本信息,并获得AppID和AppKey。 2. 在Spring Boot后端项目中,使用Spring Security实现OAuth2认证。在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-client</artifactId> <version>5.3.4.RELEASE</version> </dependency> ``` 3. 在前端Vue项目中,使用Vue CLI创建项目,并安装vue-cli-plugin-qrcode实现生成二维码。在Terminal中运行以下命令: ``` vue create qq-login-demo cd qq-login-demo vue add qrcode ``` 4. 在Spring Boot后端项目中,实现OAuth2的配置。在application.yml文件中添加以下配置: ```yaml spring: security: oauth2: client: registration: qq: clientId: <your app id> clientSecret: <your app key> redirectUriTemplate: "{baseUrl}/login/oauth2/code/{registrationId}" authorizationUri: https://graph.qq.com/oauth2.0/authorize tokenUri: https://graph.qq.com/oauth2.0/token userInfoUri: https://graph.qq.com/user/get_user_info scope: - get_user_info provider: qq: authorizationUri: https://graph.qq.com/oauth2.0/authorize tokenUri: https://graph.qq.com/oauth2.0/token userInfoUri: https://graph.qq.com/user/get_user_info?oauth_consumer_key={clientId}&openid={oauthId} userNameAttribute: nickname ``` 5. 在前端Vue项目中,实现二维码生成。在App.vue文件中添加以下代码: ```vue <template> <div id="app"> <div v-if="!isLogin"> <qrcode :value="qrCodeUrl"></qrcode> </div> <div v-else> <p>{{ userInfo.nickname }}</p> <img :src="userInfo.figureurl_qq_1" alt="头像"> </div> </div> </template> <script> import QRCode from 'qrcode' export default { name: 'App', data() { return { isLogin: false, qrCodeUrl: '' } }, mounted() { this.generateQRCode() }, methods: { async generateQRCode() { const response = await this.$http.get('/qq-login/qr-code') if (response.status === 200) { this.qrCodeUrl = response.data this.isLogin = false } }, async checkLoginStatus() { const response = await this.$http.get('/qq-login/check-login-status') if (response.status === 200) { this.userInfo = response.data this.isLogin = true } } } } </script> ``` 6. 在Spring Boot后端项目中,实现二维码生成和登录状态检查。在QqLoginController.java文件中添加以下代码: ```java @RestController @RequestMapping("/qq-login") public class QqLoginController { private final OAuth2AuthorizedClientService authorizedClientService; private final RestTemplate restTemplate; @Autowired public QqLoginController(OAuth2AuthorizedClientService authorizedClientService, RestTemplate restTemplate) { this.authorizedClientService = authorizedClientService; this.restTemplate = restTemplate; } @GetMapping("/qr-code") public String generateQRCode() { String qrCodeUrl = "https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=<your app id>&redirect_uri=http://localhost:8080/login&state=<random state>"; try { qrCodeUrl = QRCode.from(qrCodeUrl).to(ImageType.PNG).withSize(250, 250).stream().collect(Collectors.toBase64String); } catch (WriterException | IOException e) { e.printStackTrace(); } return "data:image/png;base64," + qrCodeUrl; } @GetMapping("/check-login-status") public Map<String, Object> checkLoginStatus() { OAuth2AuthenticationToken authenticationToken = (OAuth2AuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); OAuth2AuthorizedClient authorizedClient = authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName()); String accessToken = authorizedClient.getAccessToken().getTokenValue(); String openId = restTemplate.getForObject("https://graph.qq.com/oauth2.0/me?access_token=" + accessToken, String.class); openId = StringUtils.substringBetween(openId, "\"openid\":\"", "\"}"); Map<String, Object> userInfo = restTemplate.getForObject("https://graph.qq.com/user/get_user_info?access_token=" + accessToken + "&oauth_consumer_key=<your app id>&openid=" + openId, Map.class); return userInfo; } } ``` 7. 在前端Vue项目中,实现登录状态检查。在App.vue文件中添加以下代码: ```vue <script> export default { name: 'App', data() { return { isLogin: false, qrCodeUrl: '' } }, mounted() { this.generateQRCode() this.checkLoginStatus() setInterval(() => { this.checkLoginStatus() }, 3000) }, methods: { async checkLoginStatus() { const response = await this.$http.get('/qq-login/check-login-status') if (response.status === 200) { this.userInfo = response.data this.isLogin = true } } } } </script> ``` 至此,我们就成功地实现了Spring Boot+Vue代码实现第三方QQ登录的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ibun.song

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值