Bravi
Bravi

Reputation: 773

Using JWT in Laravel

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:

When the user logs in to the app, do I pass user details via JWT? For example, the name,email and user permissions.

Do I need to pass everything via JWT? For example, getting the page specific data from the database or getting all blog posts or something similar to that.

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?

I'm using Tymon/JWT-Auth library in this case and here is a little demonstration of how my application works at the moment:

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. 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. The user data is stored in a user object.

User goes to the let's say blogs page. This page sends a GET request to the server, that retrieves all the posts: /blogs?token=[THAT_GLOBAL_VARIABLE_HERE] The server returns the list of all the posts. The global token variable is updated with whatever is in the Bearer key in the header.

Is this the correct way of doing it?

Upvotes: 1

Views: 1123

Answers (1)

dotty
dotty

Reputation: 41523

When the user logs in to the app, do I pass user details via JWT? Yes. The User model is inside token.

How can I get the user details from the token? This is answered here. You pass a token and call the authenticate() method. That'll return the User model based on the token. From there your code is the same with or without a JWT.

In short, you login into your app the traditional way (form based), then you give the user a token. In this token is the User model and any additional data you want to save in it. From that point on every JSON based request needs that token to determine what user is requesting it.

Upvotes: 1

Related Questions