当前位置:网站首页>Nodejs realizes the third-party login of Weibo
Nodejs realizes the third-party login of Weibo
2022-07-06 06:04:00 【Selenium.】
List of articles
Access to Weibo, third-party login can be free of registration , Better user experience , We'll use it today nodejs Realize the third-party login of Weibo ( You can also use other languages ).
Realization effect
Online examples : http://www.lolmbbs.com/login
- Click the Weibo login button to login

- Scan the code and log in directly

Concrete realization
One 、 apply weibo Website access
Sign in https://open.weibo.com/connect apply web Website access
When developing locally, the application address should be written :127.0.0.1


Two 、 Click the button Weibo login
use OAuth2.0 to grant authorization , Refer to the documentation for details 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: After the application is created successfully weibo Give you the appKey
redirectUrl: Jump to your front-end page after successful user authorization , I wrote here http://127.0.0.1:8080/login
2. Authorization page Jump , Get users code
After the user is authorized to log in , Will jump to your last step redirectUrl, And bring users code,url Be similar to http://127.0.0.1:8080/login?code=abcdef
vue Monitor route url, If url There are code Go to the login callback interface of the back end
created() {
const {
code } = this.$route.query;
if (code) {
loginCallback({
code }).then((res) => {
this.$message({
message: `${
res.nickname} Welcome `,
type: "success",
});
this.setUser(res);
this.$router.push("/tool/qr");
});
}
}
3. Back end login callback interface , Through users code obtain accessToken, Re pass accessToken Get user information , To complete the login
async loginCallback(ctx) {
let {
code } = ctx.request.body
if (!code) {
return ctx.error(errCode.PARAMS_ERROR, ' Parameter error ')
}
// obtain 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()
// adopt accessToken obtain 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()
// Create in your own system User
let [user, isCreate] = await WeiboUser.upsert({
id, nickname, avatar })
// Generate login Token, adopt userType Distinguish between Weibo login users and system account login users
const token = await jwt.createToken({
...user.toJSON(), userType: 'weiboUser' })
return ctx.success({
nickname, avatar, token })
}
3、 ... and 、 Weibo scanning code login
1. Generate QR code for Weibo scanning and login
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 })
}
Back to url It's the QR code of Weibo login url,vcode It is equivalent to the unique identification of this QR code , Used to query whether the user scans the code
2. The front end keeps polling , Check whether this QR code is authorized by scanning
front end :
const id = setInterval(() => {
getWeiboLoginQrStatus({
vcode }).then((res) => {
const {
status, url } = res;
if (status === "3") {
window.location = url;
clearInterval(id);
}
});
}, 3000);
Back end :
async getWeiboLoginQrStatus(ctx) {
const {
vcode } = ctx.request.query
if (!vcode) {
return ctx.error(errCode.PARAMS_ERROR, ' Parameter 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 status by 3, The code user has scanned the code and authorized , Back at the same time url That is, the front-end callback after clicking the button to log in url. The next step is to 2. Authorization page Jump , Get users code It's as like as two peas .
边栏推荐
- Novice entry SCM must understand those things
- LAN communication process in the same network segment
- Accélération de la lecture vidéo de l'entreprise
- Station B Liu Erden softmx classifier and MNIST implementation -structure 9
- Auto. JS learning notes 17: basic listening events and UI simple click event operations
- Interface test: what are the components of the URL in fiddler
- isam2运行流程
- Function of contenttype
- Significance of unit testing
- Grant Yu, build a web page you want from 0
猜你喜欢

【Postman】Collections-运行配置之导入数据文件

養了只小猫咪

The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower

Wib3.0 leapfrogging, in leapfrogging (ง • ̀_•́) ง

Baidu online AI competition - image processing challenge: the 8th program of handwriting erasure

Hongliao Technology: how to quickly improve Tiktok store
![[happy Spring Festival] if you feel happy, dance](/img/b5/faa4cb94ef5fb45b8bb98ecb69962f.jpg)
[happy Spring Festival] if you feel happy, dance

SQLMAP使用教程(三)实战技巧二

Usage of test macro of GTEST

Significance of unit testing
随机推荐
Report on the competition status and investment decision recommendations of Guangxi hospital industry in China from 2022 to 2028
Title 1093: character reverse order
Caused by:org.gradle.api.internal.plugins . PluginApplicationException: Failed to apply plugin
nodejs实现微博第三方登录
Report on market depth analysis and future trend prediction of China's arsenic trioxide industry from 2022 to 2028
H3C firewall rbm+vrrp networking configuration
Testing and debugging of multithreaded applications
[leetcode] day96 - the first unique character & ransom letter & letter ectopic word
养了只小猫咪
Station B, Mr. Liu Er - multiple logistic regression, structure 7
Practice sharing: how to safely and quickly migrate from CentOS to openeuler
Hongliao Technology: Liu qiangdong's "heavy hand"
单元测试的意义
授予渔,从0开始搭建一个自己想要的网页
Gtest之TEST宏的用法
Web service connector: Servlet
C language bubble sort
Buuctf-[bjdctf2020]zjctf, but so (xiaoyute detailed explanation)
GTSAM中李群的運用
H3C V7版本交换机配置IRF