简体   繁体   English

在Laravel 5.1 API中使用JWT

[英]Using JWT in laravel 5.1 api

I'm trying to implement a nice JWT based api, so I have already read loads of documentation about JWTs and how they work, but I can't figure out a few things: 我正在尝试实现一个不错的基于JWT的api,因此我已经阅读了许多有关JWTs及其工作方式的文档,但是我无法弄清楚一些事情:

  1. When the user logs in to the app, do I pass user details via JWT ? 当用户登录到应用程序时,我是否通过JWT传递用户详细信息? For example, the name, email and user permissions . 例如, name,电子邮件和用户permissions

  2. Do I need to pass everything via JWT ? 我需要通过JWT传递所有内容吗? For example, getting the page specific data from the database or getting all blog posts or something similar to that. 例如,从数据库获取页面特定的数据或获取所有博客文章或类似内容。

  3. How do I find out on back-end whether the user has a permission to do this action or not? 如何在后端查找用户是否具有执行此操作的权限? How can I get the user details from the token? 如何从令牌中获取用户详细信息?

  4. I'm using Tymon/JWT-Auth library in this case and here is a little demonstration of how my application works at the moment: 在这种情况下,我正在使用Tymon/JWT-Auth库,这是目前我的应用程序工作方式的一些演示:

    1. User sends a post request to api/authenticate route, which logs the user in and returns a JWT token as json along with the user details - name , email and permissions . 用户向api/authenticate路由发送post请求,该请求登录用户并返回JWT令牌作为json以及用户详细信息- nameemailpermissions So the data returned from the server looks like this: 因此,从服务器返回的数据如下所示:

    { "token": "blablabla", "user": { "email": "testin@test.com", "name": "Test User", "permissions": [ "can_edit_posts", "can_delete_users" ] } }

    JWT is stored in a global variable in javascript called token . JWT存储在javascript中称为token的全局变量中。 The user data is stored in a user object. 用户数据存储在用户对象中。

    1. User goes to the let's say blogs page. 用户转到“ blogs页面。 This page sends a GET request to the server, that retrieves all the posts: /blogs?token=[THAT_GLOBAL_VARIABLE_HERE] 该页面向服务器发送GET请求,该请求检索所有帖子: /blogs?token=[THAT_GLOBAL_VARIABLE_HERE]
    2. The server returns the list of all the posts. 服务器返回所有帖子的列表。
    3. The global token variable is updated with whatever is in the Bearer key in the header. 全局令牌变量将使用标头中Bearer键中的任何内容进行更新。

Is this the correct way of doing it? 这是正确的做法吗?

您必须将令牌附加到称为Authorization的特殊http标头中,例如使用以下模式:

headers('Authorization: JWT aer5a4era456f4asrgt1aer46a');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM