Laravel 护照 - 来宾令牌

Laravel Passport - Guest Token

假设有一个应用程序有 10 个动态页面(可能是表单),其中 8 个页面是受限制的(需要用户在应用程序中登录),另外 2 个页面可供匿名用户使用。

我的前端应用程序是在 Angular 2 开发的,后端 API 是在 Laravel 5.4 开发的。我对 JWT 令牌更着迷,发现 laravel 通过护照提供内置支持。

问题:

  1. 对于这 8 个受限制的页面,我可以轻松地使用 password grant tokens。但是我如何为我的 Angular 应用程序提供访客令牌以访问这两个页面
  2. 如何限制来宾用户访问 8 个受限页面的 API 功能。 (或者我如何检查访问的用户是访客还是在 API 结束时登录的用户)

Note: I cannot use Personal Access Tokens as it will allow my app to use any restricted API feature.

我用过JWT approach here. In my case, I created JWT token from my API. For those who wants to use JWT feature, they can take a look at this package。我添加了名为 "Guest" 的新有效负载并为其分配了布尔值。在我的数据库中,我添加了新用户(称为匿名用户)并将其 ID 存储在我的 laravel 配置中。

接下来,我创建了新的中间件 VerifyJwtToken,它验证用户,提取它的有效负载(使用 base64_decode)并确定它是否是来宾。现在我所有的 Laravel 路由都在这个中间件中。

接下来,我将此令牌存储在 laravel session 和 localStorage 中(以便通过 angular 访问它)。

现在,我可以轻松地从 localStorage 访问此令牌。在 Angular 结束时,我在 Angular 4 中使用了 Angular2Jwt package which helps extracting the token and identifying if it is guest or logged in user. I also created HTTP Interceptor,它在每个 API 请求中将 JWT 令牌添加为 header。