简体   繁体   中英

JWT that can be encoded in Laravel and decoded in JavaScript

I am trying to generate a JWT token which I will do in my Laravel project like this solution I found: https://github.com/luciferous/jwt/blob/master/JWT.php

So I have 2 questions I am trying to get wrap my head around:

In my Next.js React project, i would set the JWT in a cookie to remember it. Is that right? And then can pass it with every request to the server to verify the user.

How could I decode it then in Next.js? So that I could get some basic info out of it like a username.

For JWT Decoding in Javascript you could use Auth0's JWT decode library( https://github.com/auth0/jwt-decode ) which makes it simple to decode(no verification) encoded JWT tokens.

You would just read the JWT token from the set cookie and decode it like this:

var token = 'eyJ0eXAiO.../// jwt token';
var decoded = jwt_decode(token);

You can also use a simple function to decode it which would look like this:

function parseJwt (token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace('-', '+').replace('_', '/');
    return JSON.parse(window.atob(base64));
};

There is no problem with decoding JWT tokens directly in the React application, just make sure that you always verify the encoded token on the server side so it can't be a modified JWT token by the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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