前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >怎么使用slim-jwt-auth对API进行身份验证

怎么使用slim-jwt-auth对API进行身份验证

作者头像
许杨淼淼
发布2018-07-11 15:11:13
1.9K0
发布2018-07-11 15:11:13
举报
文章被收录于专栏:醉程序

这两天一直想找个机会做一下API的身份验证,就像微博那样提供接口给别人用,但又有所限制,也不会导致接口滥用。 大概一年半之前,写了个大学英语四六级成绩查询的接口(由于历史原因,此Github帐号不再使用了,新的在这里),托管在新浪云,放到了网上,也没有加任何限制,结果被一个人短时间内多次调用,真的是非常频繁,浪费了不少云豆。现在正好可以用之前写的成绩查询接口来做这个身份验证的实验。

准备工作

在做一个二维码签到/点名系统时,需要后台同时支持移动端、PC端和网页版,因此决定写成接口,这样比较方便。既然写成接口,就写的规范一些咯,之前自己写的小玩意实在是拿不出手,毫无规范可言。了解到RESTful API,查了一些资料,主要看了这篇, 写的很不错。然后就去找个框架呗。 在写二维码签到/点名系统时,用的是CI框架,也有第三方的REST库, 但用的很不爽,说不上来的不得劲。经过查询,知道了slim这个框架,是专门构建RESTful API的框架。之后就开始了一天的折腾。

安装框架和用到的第三方组件

官方推荐使用composer进行安装,下面不说废话了,Come on Install composer Slim and some third plugins

代码语言:javascript
复制
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin --filename=composer        // install composercomposer require slim/slim "^3.0"        // install Slimcomposer require tuupola/slim-basic-auth "^2.0"        // install slim-basic-authcomposer require lcobucci/jwt "^3.1"        // install jwtcomposer require tuupola/slim-jwt-auth "^2.0"        // install slim-jwt-auth

啰嗦一句,windowns上面进行开发比较麻烦,建议装个虚拟机跑ubuntu/cenos或者你喜欢的发行版

开始码

需要注意的是,当前(2015年12月21日)时间,slim最新版本是3.0 开始之前我找了一些网上别人写的中文入门之类的博文,但大多是2.x, 会有一些坑(不禁想起了Python的版本, o(︶︿︶)o ).

根据我已经写完了的V1的示例代码来分析/学习 index.php: https://github.com/xu42/API/blob/master/index.php cet_score.php: https://github.com/xu42/API/blob/master/v1/cet_score/cet_score.php

  • Authentication Process (身份验证流程)
    • 假定使用我们的接口的人(以下称”客户”)已经注册成为会员,已经拥有获取接口使用权限的”username” 和 “password”
    • 客户向后台发送附带”username” 和 “password” 和 “key” 的请求, 请求获取接口使用权的”accecc_token”
    • 客户拿到”accecc_token”后, 向成绩查询接口发起请求同时附带”access_token”和”key”
    • 后台验证并返回相应的结果
  • Specific analysis (具体分析)
    • 定义获取”access_token”的URL是”https://ip/token“, 除了这个URL其它都应该需要验证身份。在Github上查看代码 123456789101112$app->add(new JwtAuthentication([ "secret" => "cn.xu42.api", "rules" => [ new JwtAuthentication\RequestPathRule([ "path" => '/', "passthrough" => ["/token"] ]) ], "callback" => function(ServerRequestInterface $request, ResponseInterface $response, $arguments) use ($app) { $app->jwt = $arguments["decoded"]; }]));
    • 这一步的验证是”Basic Auth”方式(已经很少有再用”Basic Auth”了, 因为有更好的”OAuth 2.0”替代), 因为是个示例, 直接把”username” 和 “password”写死在了代码里, 规模大了应该写在数据库里。在Github上查看代码 123456$app->add(new HttpBasicAuthentication([ "path" => "/token", "users" => [ "user0" => "user0password" ]]));
    • 客户向 https://ip/token 发起GET 请求, 后台生成”access_token”。在Github上查看代码 123456789101112131415161718$app->get("/token", function(ServerRequestInterface $request, ResponseInterface $response, $arguments) use ($app) { if(!$request->hasHeader('key')){ return $response->withStatus(401); } $access_token = (new Builder())->setIssuer('https://api.xu42.cn') // Configures the issuer (iss claim) ->setAudience('https://api.xu42.cn') // Configures the audience (aud claim) ->setId($request->getHeaderLine('key'), true) // Configures the id (jti claim), replicating as a header item ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim) ->setNotBefore(time()+60) // Configures the time that the token can be used (nbf claim) ->setExpiration(time()+3600) // Configures the expiration time of the token (exp claim) ->set('scope', ['read']) // Configures a new claim, called "scope" ->sign(new \Lcobucci\JWT\Signer\Hmac\Sha256(), 'cn.xu42.api') // ALGORITHM HS256 ->getToken(); // Retrieves the generated token $response = $response->withStatus(200); $response = $response->withHeader('Content-type', 'application/json'); $response->getBody()->write(json_encode(['access_token' => (string) $access_token, 'token_type' => 'bearer', 'expires_in' => $access_token->getClaim('exp') - $access_token->getClaim('iat')])); return $response;});
    • 客户请求成绩查询接口, 需要验证”access_token” 和 “key”, 并返回结果。在Github上查看代码 12345678$app->get('/v1/cet_score/{name}/{numbers}', function (ServerRequestInterface $request, ResponseInterface $response, $args) use ($app) { if(in_array('read', $app->jwt->scope) && $app->jwt->jti == $request->getHeaderLine('key')) { require_once 'v1/cet_score/cet_score.php'; return cet_score::get($request, $response, $args); } else { return $response->withStatus(401); }});

整个流程就是这样,不难,代码量也不大,第一次完成了还像样的接口,还是挺高兴的。但也明白,这跟真实企业级的接口比,差的还很远,继续努力。

参考资料

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 准备工作
    • 安装框架和用到的第三方组件
    • 开始码
    相关产品与服务
    Serverless HTTP 服务
    Serverless HTTP 服务基于腾讯云 API 网关 和 Web Cloud Function(以下简称“Web Function”)建站云函数(云函数的一种类型)的产品能力,可以支持各种类型的 HTTP 服务开发,实现了 Serverless 与 Web 服务最优雅的结合。用户可以快速构建 Web 原生框架,把本地的 Express、Koa、Nextjs、Nuxtjs 等框架项目快速迁移到云端,同时也支持 Wordpress、Discuz Q 等现有应用模版一键快速创建。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档