做Yii2-Restful-API授权验证,token正常获取,header请求一直401,困扰啊!
检查代码有没有问题啊,不然我也很无奈,好了开始探索。
环境:WAMP
首先我是正常获取token
访问http://localhost/advanced/api/web/v1/users/user-profile出现401
咋整啊,追溯呗,header在哪里验证就往哪走,从哪下手啊?authenticator对应class呗。
public function behaviors() { return ArrayHelper::merge (parent::behaviors(), [ 'authenticator' => [ 'class' => HttpBearerAuth::className(), 'optional' => [ 'login', 'signup-test', ], ] ] ); }
追溯HttpBearerAuth
找到authenticate方法,发现$authHeader = $request->getHeaders()->get('Authorization');
那就打个日志看看$authHeader有没有获取到Header
Yii::info('authHeader=' . json_encode($authHeader), 'test');
如果有,那就别往下看了,再检查下token是不是写错了,检查下authenticate方法,检查下代码。
header都传过来了,那就看下自己的逻辑问题吧。
我的结果:authHeader=NULL
那就硬编码测试下
删除Authorization再次访问http://localhost/advanced/api/web/v1/users/user-profile成功。
这说明我们的代码逻辑没有问题
$authHeader = $request->getHeaders()->get('Authorization');
$request->getHeaders(),header没有get到。
然后问度娘呗
参考:github:https://github.com/yiisoft/yii2/issues/6631
大概是Apache的问题吧
在.htaccess中添加SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
注释硬编码再次访问http://localhost/advanced/api/web/v1/users/user-profile
源码
链接:https://pan.baidu.com/s/1pMhPfsB 密码:9vsq