当前位置:网站首页>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 .
边栏推荐
- [leetcode] day96 - the first unique character & ransom letter & letter ectopic word
- Download, install and use NVM of node, and related use of node and NRM
- CoDeSys note 2: set coil and reset coil
- 【论文阅读】NFlowJS:基于鲁棒学习的合成负数据密集异常检测
- H3C V7版本交换机配置IRF
- Report on market depth analysis and future trend prediction of China's arsenic trioxide industry from 2022 to 2028
- 【C语言】字符串左旋
- HCIA复习
- Classes and objects (I) detailed explanation of this pointer
- Mysql database master-slave cluster construction
猜你喜欢
Application du Groupe Li dans gtsam
C language learning notes (mind map)
nodejs实现微博第三方登录
Station B Liu Erden softmx classifier and MNIST implementation -structure 9
VINS-Mono: A Robust and Versatile Monocular Visual-Inertial State Estimator
P2802 go home
Baidu online AI competition - image processing challenge: the 8th program of handwriting erasure
华为BFD的配置规范
【论文代码】SML部分代码阅读
Raised a kitten
随机推荐
Station B, Master Liu Er - back propagation
华为路由器如何配置静态路由
Seven imperceptible truths in software testing
[Thesis code] SML part code reading
Raised a kitten
在线问题与离线问题
Auto. JS learning notes 17: basic listening events and UI simple click event operations
IPv6 comprehensive experiment
数学三大核心领域概述:几何
HCIA review
[untitled]
【无标题】
Embedded interview questions (I: process and thread)
[C language syntax] the difference between typedef struct and struct
GTSAM中ISAM2和IncrementalFixedLagSmoother说明
Redis6 cluster setup
Web service connector: Servlet
Implementation of linked list in address book management system
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
【LeetCode】Day96-第一个唯一字符&赎金信&字母异位词