接入微博第三方登錄可以免注冊,對用戶的體驗更好,今天我們就用nodejs實現微博第三方登錄(用其它語言也可以)?!鞠嚓P教程推薦:nodejs視頻教程】
在線實例: http://www.lolmbbs.com/login
【資料圖】
1、點擊微博登錄按鈕登錄
2、直接掃碼登錄
具體實現
登錄https://open.weibo.com/connect申請web網站接入本地開發的時候應用地址寫:127.0.0.1
采用OAuth2.0授權,詳細可參考文檔https://open.weibo.com/wiki/Connect/login
const weiboUrl = `https://api.weibo.com/oauth2/authorize?client_id=${weiboConfig.appKey}&response_type=code&redirect_uri=${weiboConfig.redirectUrl}`
appKey: 創建應用成功后weibo給你的appKey redirectUrl: 用戶授權成功后跳轉的你的前端頁面,我這里寫的是http://127.0.0.1:8080/login
用戶授權登錄后,會跳轉到你上一步寫的redirectUrl,并帶上用戶code,url類似于http://127.0.0.1:8080/login?code=abcdef
vue監聽路由url,如果url上有code就去請求后端的登錄回調接口
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"); }); } }
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 }) }
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 })}
返回的url就是微博登錄二維碼url,vcode相當于此二維碼唯一標識,用來查詢用戶是否掃碼
前端:
const id = setInterval(() => { getWeiboLoginQrStatus({ vcode }).then((res) => { const { status, url } = res; if (status === "3") { window.location = url; clearInterval(id); } });}, 3000);
后端:
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 }) }
如果status為3,代碼用戶已經掃碼授權了,同時返回的url即點擊按鈕登錄后的前端回調url。之后的步驟就跟2. 授權頁面跳轉,獲取用戶code一模一樣了.
更多node相關知識,請訪問:nodejs 教程!
以上就是淺析node怎么進行微博第三方登錄的詳細內容,更多請關注php中文網其它相關文章!