1. 集成jwt:
RPC服务之间就不做用户验证了,由网关统一来处理用户身份认证.
(1). jwt github:
github.com/firebase/php-jwt
# 安装:
php composer.phar require firebase/php-jwt --ignore-platform-reqs
(2). 原理:
①. 以http程序或前端在调用程序时,统一要进入网关,一般需要一个身份验证.
②. 常见做法是通过后端url参数或头信息传一个token的方式给网关,网关解析正常后,会把参数传给RPC服务.
③. 过程:
a. 客户端需要专门的API提供用户获取token并保存,服务端也要把token保存到redis中.
b. 在客户端提交请求时,需要在头加个token值,后台进行比对token是否正确.
2. 验证字段:
app\Validator\TokenValidator.php:
namespace App\Validator;
use Swoft\Validator\Annotation\Mapping\IsString;
use Swoft\Validator\Annotation\Mapping\Pattern;
use Swoft\Validator\Annotation\Mapping\Validator;
/**
* @Validator(name="tokenValidator")
*/
class TokenValidator {
/**
* @var string
* @IsString()
* @Pattern(regex="/^[a-zA-Z]\w{5,19}$/", message="用户名规则不正确")
*/
protected $username;
/**
* @var string
* @IsString()
* @Pattern(regex="/^.{6,18}$/", message="密码规则不正确")
*/
protected $password;
}
3. 增加自定义Exception:
app\Exception\TokenHandler.php:
namespace App\Exception;
use Swoft\Error\Annotation\Mapping\ExceptionHandler;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Exception\Handler\AbstractHttpErrorHandler;
use Throwable;
/**
* @ExceptionHandler(Swoft\Validator\Exception\ValidatorException::class)
*/
class TokenHandler extends AbstractHttpErrorHandler{
/**
* @param Throwable $e
* @param Response $response
* @return Response
*/
public function handle(Throwable $e, Response $response): Response
{
return $response->withData(["errcode" => 40013, "errmsg" => $e->getMessage()]);
}
}
注:
①. 为什么TokenHandler类的ExceptionHandler注解要传以下这个:
@ExceptionHandler(Swoft\Validator\Exception\ValidatorException::class)