oAuth授权

91 阅读1分钟

背景

前段时间升级了公司的登录功能,就是把学生登录和老师登录的地址区分开来。想到现在普遍使用的oAth登录。所以今天学习下并记录之。

oAth步骤(以gitee为例)

1. 先在gitte上创建自己的应用,创建地址

gitee创建应用

image.png

创建完成后会生成两个数据 image.png

2. 创建一个本地的服务(我为了方便测试)。

我使用的阮一峰老师的demo修改githubdemo

3. 使用浏览器打开gitte的授权页面,格式如下:

// authorize_uri gitee的地址
// client_id 申请服务的时候生成的参数
// redirect_uri自己的服务的接口,提供给gitee调用
`${authorize_uri}?client_id=${client_id}&redirect_uri=${redirect_uri}`;

用户同意后,即用户授权,gitee调用我们自己的服务器接口/oauth/redirect

4. gitee调用我们自己的服务器接口/oauth/redirect给我们发送access_token

// 接口返回数据
{
  access_token: '1f5171569f0604aba9e2405f89eedd9c',
  token_type: 'bearer',
  expires_in: 86400,
  refresh_token: '5900b9a4c42210d93c20a7bdd72dbb40505dbeedca42396d981cbdab36ce5926',
  scope: 'user_info',
  created_at: 1645600684
}

5. 我们使用access_token去gitee请求用户的数据

const result = await axios({
    method: "get",
    url: `https://gitee.com/api/v5/user`,
    headers: {
      accept: "application/json",
      Authorization: `token ${accessToken}`,
    },
  });
  console.log(result.data);
  const name = result.data.name;

  ctx.response.redirect(`/welcome.html?name=${name}`);

refresh_token的几个问题(待实践)

  1. 后端如何实现refresh_token,参考
  2. 前端实现 参考
  3. 使用jwt如何实现 参考

完整服务端代码

const client_id = "xxxx";
const client_secret = "xxxxx";
const redirect_uri = 'http://192.168.56.1:8080/oauth/redirect';

const Koa = require("koa");
const path = require("path");
const serve = require("koa-static");
const route = require("koa-route");
const axios = require("axios");

const app = new Koa();

const main = serve(path.join(__dirname + "/public"));

const oauth = async (ctx) => {
  const code = ctx.request.query.code;
  console.log("authorization code:", code,ctx.request);
  const tokenResponse = await axios({
    method: "post",
    url:`https://gitee.com/oauth/token?grant_type=authorization_code&code=${code}&client_id=${client_id}&redirect_uri=${redirect_uri}&client_secret=${client_secret}`,
    headers: {
      accept: "application/json",
    },
  });

  const accessToken = tokenResponse.data.access_token;
  console.log(`access token: ${accessToken}`);

  const result = await axios({
    method: "get",
    url: `https://gitee.com/api/v5/user`,
    headers: {
      accept: "application/json",
      Authorization: `token ${accessToken}`,
    },
  });
  console.log(result.data);
  const name = result.data.name;

  ctx.response.redirect(`/welcome.html?name=${name}`);// 重定向
};

app.use(main);
app.use(route.get("/login", oauth));

app.listen(8080);

客户端代码

 <a id="login">Gitee登录</a>

<script>
  // fill in your cliend_id
  const client_id = 'xxxx';

  const authorize_uri = 'https://gitee.com/oauth/authorize';
  const redirect_uri = 'http://192.168.56.1:8080/login';

  const link = document.getElementById('login');
  link.href = `${authorize_uri}?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=code`;
</script>