[Vuejs]-Vuejs – using JWT as param in vue-router

0πŸ‘

the JWT token is composed of 3 parts (header, payload, verify signature) separated by periods

HEADER: ALGORITHM & TOKEN TYPE

in base 64
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

decode base 64
{
  "alg": "HS256",
  "typ": "JWT"
}

PAYLOAD: DATA

in base 64
eyJ1c2VyX2lkIjoxLCJrZXkiOiJjMjljZDNmNjYwZDNlMWI4NjRhM2JmNjNkODQxZTc2MiIsImlhdCI6MTYxMzIzMJNTM3MCwiZXhzwjMxNjE

decode base 64
{
  "user_id": 1,
  "key": "c29cd3f660d3e1b864a3bf63d841e762",
  "iat": 1613231370,
  "exp": 1613231430
}

VERIFY SIGNATURE
IEchqNWEGAzVZEQhQQIVl9bnbGcu3I_kCXhG8nmKv2k

what matters is the payload, this is sent through the url, and use it.

now if you want to recreate the complete jwt, the header will always be the same, the signature can be generated like this

HMACSHA256 (
   base64UrlEncode (header) + "." +
   base64UrlEncode (payload),
   your-256-bit-secret
)

usually password recovery services only use payload

https://jwt.io

0πŸ‘

I was fighting with the same problem and solved it by adding the token as a query parameter. That means someone would call my url as

domain.com/my-path?token=a.b.c

The example is written for vue3


const myRoute = {
  path: "my-path",
  name: "My Page",
  component: import("./App.vue"),
  beforeEnter( to, from, next ) {
    const { token } = to.query;
    if (typeof token === "string") {
      const jwtRegEx = /(^[A-Za-z0-9-_]*\.[A-Za-z0-9-_]*\.[A-Za-z0-9-_]*$)/;
      const match = token.match(jwtRegEx);
      if (match === null) {
        next(false);
      } else {
        next();
      }
    } else {
      next(false);
    }
  },
};

The beforeEach function is there to check that the token is indeed a jwt.

Leave a comment