Home  >  Article  >  Web Front-end  >  A brief analysis of how node performs third-party login on Weibo

A brief analysis of how node performs third-party login on Weibo

青灯夜游
青灯夜游forward
2022-11-01 19:34:161682browse

How to perform third-party login on Weibo? The following article will introduce to you how to use node to implement third-party login on Weibo. I hope it will be helpful to you!

A brief analysis of how node performs third-party login on Weibo

You can access Weibo third-party login without registration, which provides a better user experience. Today we will use nodejs to implement Weibo third-party login (other languages ​​are also available) ). [Related tutorial recommendations: nodejs video tutorial]

Achieve effect

Online example: http://www. lolmbbs.com/login

1. Click the Weibo login button to log in

A brief analysis of how node performs third-party login on Weibo

2. Scan the QR code to log in

Specific implementation

1. Apply for weibo website access

Log in to https://open.weibo.com/connect to apply for web website When accessing
for local development, write the application address: 127.0.0.1

A brief analysis of how node performs third-party login on Weibo
A brief analysis of how node performs third-party login on Weibo
A brief analysis of how node performs third-party login on Weibo

##2. Click the button to log in to Weibo

uses OAuth2.0 authorization. For details, please refer to the document https://open.weibo.com/wiki/Connect/login

1. Generate Weibo login authorization verification code
const weiboUrl = `https://api.weibo.com/oauth2/authorize?client_id=${weiboConfig.appKey}&response_type=code&redirect_uri=${weiboConfig.redirectUrl}`
appKey: The appKey given to you by weibo after successfully creating the application

redirectUrl: Your front-end page that will be redirected after successful user authorization. I What is written here is http://127.0.0.1:8080/login

2. The authorization page will jump. After obtaining the user code
, the user will be authorized to log in, and it will jump to the previous step you wrote. redirectUrl, and bring the user code, the url is similar to http://127.0.0.1:8080/login?code=abcdef

vue listens to the routing url, and if there is a code on the url, it will request the back-end login callback Interface

created() {
    const { code } = this.$route.query;
    if (code) {
      loginCallback({ code }).then((res) => {
        this.$message({
          message: `${res.nickname} 欢迎您`,
          type: "success",
        });
        this.setUser(res);
        this.$router.push("/tool/qr");
      });
    }
  }

3. Backend login callback interface, obtain accessToken through user code, and then obtain user information through accessToken to complete login
   async loginCallback(ctx) {
      let { code } = ctx.request.body
      if (!code) {
         return ctx.error(errCode.PARAMS_ERROR, '参数错误')
      }
      // 获取accessToken
      const { access_token, uid } = await got.post('https://api.weibo.com/oauth2/access_token', {
         form: {
            client_id: weiboConfig.appKey,
            client_secret: weiboConfig.appSecret,
            grant_type: 'authorization_code',
            redirect_uri: weiboConfig.redirectUrl,
            code
         }
      }).json()
      // 通过accessToken获取UserInfo
      const { id, name: nickname, avatar_hd: avatar } = await got.get(`https://api.weibo.com/2/users/show.json?access_token=${access_token}&uid=${uid}`).json()
      // 在自己的系统内创建User
      let [user, isCreate] = await WeiboUser.upsert({ id, nickname, avatar })
      // 生成登录Token,通过userType区分是微博登录用户还是系统账号登录用户
      const token = await jwt.createToken({ ...user.toJSON(), userType: 'weiboUser' })
      return ctx.success({ nickname, avatar, token })
   }

3. Weibo scan code Login

1. Generate Weibo scan code login QR code
 async getWeiboLoginQr(ctx) {
      const qrApi = `https://api.weibo.com/oauth2/qrcode_authorize/generate?client_id=${weiboConfig.appKey}&redirect_uri=${weiboConfig.redirectUrl}&scope=&response_type=code&state=&__rnd=${Date.now()}`
      const { url, vcode } = await got.get(qrApi).json()
      return ctx.success({ weiboQrUrl: url, vcode })
}
The returned url is the Weibo login QR code url, vcode is equivalent to this QR code Unique identifier, used to check whether the user has scanned the code

2. The front end continuously polls to check whether the QR code is authorized by scanning the code
Front end:

 const id = setInterval(() => {
          getWeiboLoginQrStatus({ vcode }).then((res) => {
            const { status, url } = res;
            if (status === "3") {
              window.location = url;
              clearInterval(id);
            }
          });
}, 3000);
End:

   async getWeiboLoginQrStatus(ctx) {
      const { vcode } = ctx.request.query
      if (!vcode) {
         return ctx.error(errCode.PARAMS_ERROR, '参数错误')
      }
      const queryQrApi = `https://api.weibo.com/oauth2/qrcode_authorize/query?vcode=${vcode}&__rnd=${Date.now()}`
      const { status, url } = await got(queryQrApi).json()
      return ctx.success({ status, url })
   }
If the status is 3, the code user has scanned the code to authorize, and the URL returned at the same time is the front-end callback URL after clicking the button to log in. The subsequent steps are exactly the same as 2. Jump to the authorization page and obtain the user code.

For more node-related knowledge, please visit:

nodejs tutorial!

The above is the detailed content of A brief analysis of how node performs third-party login on Weibo. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete