YAPI配置Gitlab登录

1,957 阅读3分钟

前言

YAPI 作为优秀的接口管理工具,尤其是可以在内网部署,是很多小公司的选择;安装过程就不在此赘述了,详细查看下面的链接:

yapi.smart-xwork.cn/doc/devops/…

YAPI内置一套用户系统,虽然可以配置LDAP授权,但是很多企业并没有相关的用户中心可以对接,所以我们这里选择接入Gitlab授权,因为Gitlab应该是大部分的公司都会搭建的平台。并且YAPI也是给程序员去使用的,使用Gitlab登录比较简单;

实现

因为Gitlab提供了oauth2的相关接口,在Github上也找到了对应的插件方案,如下:

github.com/cyj0122/yap…

1、安装插件

进入到YAPI安装目录下的vendors文件夹,执行下面的代码安装依赖:

npm install https://github.com/cyj0122/yapi-plugin-gitlab.git --save

这里我们使用git路径安装的,如果慢可以翻墙或者将该仓库同步到Gitee上进行安装;
安装完成之后我们就要进行一下配置了;

2、配置插件

若要使用Gitlab登录,需要在Gitlab上面注册一个应用并且得到appId/appSecret等信息;
下面的 gitlab.example.com:port需要替换成自己真正部署的域名和端口;

可以查看帮助文件: http://gitlab.example.com:port/help/integration/oauth_provider.md

接下来修改YAPI安装目录下的config.js文件,plugins中添加下面的内容

"plugins": [{
    "name": "gitlab",
    "options": {
        "host" : "http://gitlab.example.com:port",
        "redirectUri" : "http://yapi.example.com:3000/api/plugin/oauth2/callback",
        "appId" : "xxxxxxxxxxxxxxxxxx",
        "appSecret" : "xxxxxxxxxxxxxxxxxxxxxx",
        "accessToken": "xxxxxxxxxxxxxxxxxxxxxxxx",
        "loginPath": "/api/v4/user",
        "authPath" : "/oauth/authorize",
        "tokenPath" : "/oauth/token",
        "emailKey" : "email",
        "userKey" : "username",
        "emailPostfix" : "@yapi.com"
    }
}]

还需要修改YAPI安装目录下vendors/client/plugin-module.js文件,添加下面的内容:

"gitlab": {
        module: require('yapi-plugin-gitlab/client.js'),
        options: {
          "host" : "http://gitlab.example.com:port",
          "redirectUri" : "http://yapi.example.com:3000/api/plugin/oauth2/callback",
          "appId" : "xxxxxxxxxxxxxxxxxx",
          "appSecret" : "xxxxxxxxxxxxxxxxxxxxxx",
          "accessToken": "xxxxxxxxxxxxxxxxxxxxxxxx",
          "loginPath": "/api/v4/user",
          "authPath" : "/oauth/authorize",
          "tokenPath" : "/oauth/token",
          "emailKey" : "email",
          "userKey" : "username",
          "emailPostfix" : "@yapi.com"
        }
    },

注意:

如果你的Gitlab版本是8.x,需要将 loginPath 设置为 /api/v3/user;在下面的地方可以看到自己的Gitlab版本,或者直接访问:http://gitlab.example.com:port/help 就可以看到

3、编译代码

这里要求使用nodejs >= 10的版本进行编译,在YAPI安装文件夹执行:

npm run  build-client

4、重启服务器

重启服务器后重新加载YAPI会发现有一个登录按钮旁边会有一个Gitlab登录的按钮,点击就可以进行登录;

常见问题

1、npm run build-client时遇到 ykit pack -m 提示编译失败

是因为swagger没有转义,要修改下YAPI安装目录vendors的ykit.config.js,在exclude中排除一下,大概在82行;

exclude: isWin ? /(tui-editor|node_modules\(?!_?(yapi-plugin|json-schema-editor-visual)))/ : /(tui-editor|node_modules/(?!_?(yapi-plugin|swagger-client|json-schema-editor-visual)))/

2、Gitlab升级到https之后会在网页显示授权失败,因为Gitlab的登录插件支持的链接是http的,所以会报错说授权失败,所以我们要修改下,将http修改https就可以了,页面报错:

查看服务器日志报错的详细信息如下所示

我们将文件 yapi安装目录下的vendors/node_modules/yapi-plugin-gitlab/controller/oauth2Controller.js 顶部引入的http换成https就可以了;修改完成之后要重启一下服务器。

知乎链接:zhuanlan.zhihu.com/p/418294329