且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel Passport-访客令牌

更新时间:2023-12-01 17:16:22

我在这里使用了 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.