Laravel Passport-访客令牌 [英] Laravel Passport - Guest Token

查看:147
本文介绍了Laravel Passport-访客令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设一个应用程序具有10个动态页面(可能是表单),其中有8个页面受到限制(要求用户登录应用程序),而2个页面可供匿名用户使用.

Let's assume there is an application with 10 dynamic pages (probably forms) out of which, 8 pages are restricted (requires user to login in application) and 2 pages are available for anonymous users.

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

My front end application is in Angular 2 and back-end API is developed in Laravel 5.4. I'm more fascinated towards JWT tokens and found that, laravel has in-built support through passport.

问题:

  1. 对于这8个受限的帐户,我可以轻松地使用密码授予令牌页.但是如何将访客令牌赋予我的Angular应用程序以访问那两个页面
  2. 如何限制来宾用户访问8个受限页面的API功能. (或者如何检查访问的用户是来宾还是在API端登录的用户)
  1. I can easily use password grant tokens for those 8 restricted page. But how do I give guest token to my Angular app for accessing those 2 pages
  2. How can I restrict guest user for accessing API features of 8 restricted page. (Or how do I check if visited user is guest or logged in user at API end)

注意::我不能使用个人访问令牌,因为它将允许我的应用 使用任何受限制的API功能.

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

推荐答案

我在这里使用了 JWT 方法.就我而言,我是通过API创建JWT令牌的.对于那些想使用JWT功能的用户,可以看看此程序包.我添加了一个称为"Guest"的新负载,并为其分配了布尔值.在数据库中,我添加了一个新用户(称为匿名用户),并将其ID存储在我的laravel配置中.

I've used 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. I added new payload called "Guest" and assigned boolean value to it. In my database, I added new user (called anonymous user) and stored the id of it in my laravel configuration.

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

Next, I created new middleware VerifyJwtToken, which validates the user, extracts it's payload (with base64_decode) and identify if it is guest. Now all of my Laravel routes are inside this middleware.

接下来,我将此令牌和 localStorage存储在laravel会话中(用于通过angular访问).

Next, I stored this token in laravel session as well as localStorage (for accessing it through angular).

现在,我可以轻松地从localStorage访问此令牌.在Angular端,我使用了 Angular2Jwt 程序包,该程序包有助于提取令牌并确定令牌是访客还是令牌.登录用户.我还在Angular 4中创建了 HTTP拦截器,它将JWT令牌添加为每个API请求中的标头.

Now, I can easily access this token from localStorage. In the Angular end i used Angular2Jwt package which helps extracting the token and identifying if it is guest or logged in user. I also created HTTP Interceptor in Angular 4 which adds JWT token as header in every API requests.

这篇关于Laravel Passport-访客令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆