第三方授权登录流程 && 实例

前言

目前很多网站都有注册登录的方式,同时他们也都有第三方授权登录,那么为什么第三方授权会有呢?

如果一个网站必须要注册登录才能访问的话,那么他的访问量会大量下降,如果不需要注册,例如使用微信和QQ去登录这个网站,是绝大多数的人的选择

原理步骤

  1. 一般第三方软件会有一个授权步骤

  2. 第三方授权的图标是一个链接,链接到授权网站,获取到token
    一般会携带一个 client_id
    还有一个回调地址 redirect_uri

  3. 回调到后台地址,根据token,就可以调用第三方授权的api接口来获取信息

const result = await axios({
    method: "get",
    url: `https://api.github.com/user`,
    headers: {
      accept: "application/json",
      Authorization: `token ${accessToken}`
    }
});
  1. 根据result获取到信息之后,然后重定向到前端,并且携带token

github实例

主要是github不需要审核等麻烦的步骤,直接就可以用,很方便




前端

<a href="https://github.com/login/oauth/authorize?client_id=更改为上面的Client ID&redirect_uri=更改为上面的回调地址">
   <img src="https://static.iiter.cn/github.ico" />
</a>

后端

index.js

const Koa = require("koa");
const router = require("koa-router")();
const app = new Koa();

router.use("/server/oauth", require("./oauth.js"));

// 加载所有路由
app.use(router.routes()); /*启动路由*/
app.use(router.allowedMethods());

app.listen(10010, () => {
  console.log(`服务器运行在10010端口上`);
});

oauth.js

const code = require("koa-router")();
const axios = require("axios");
const clientID = "f4f827cfbebe51a858b8";    //更改为自己的ID
const clientSecret = "886840688d944d5afd0da2e7be5b5f1d0758b1b2";   //更改为自己的秘钥

code.get("/github", async ctx => {
  const requestToken = ctx.request.query.code;
  const tokenResponse = await axios({
    method: "post",
    url:
      "https://github.com/login/oauth/access_token?" +
      `client_id=${clientID}&` +
      `client_secret=${clientSecret}&` +
      `code=${requestToken}`,
    headers: {
      accept: "application/json"
    }
  });

  const accessToken = tokenResponse.data.access_token;
  const result = await axios({
    method: "get",
    url: `https://api.github.com/user`,
    headers: {
      accept: "application/json",
      Authorization: `token ${accessToken}`
    }
  });
  console.log(result.data)  // 这个就是获取到的数据
  ctx.response.redirect(   
    // 这里重定向到自己的前端服务器  
    `http://taro.shtodream.cn/pages/my/index?name=${result.data.name}&avatar=${result.data.avatar_url}&token=${accessToken}`
  );
});

module.exports = code.routes();

我的实例网站

完整代码

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值