user6823414
user6823414

Reputation:

How do you change what gets displayed on a front-end (Angular) view based on properties in your JWT token?

I'm pretty new to working with tokens. Just started learning yesterday.

I have an Express backend API. I understand that the token prevents anyone from getting access to data on any given API endpoint/json data...But how can I READ/decrypt the JWT when it's on the angular side?

I.E., Okay, I know that this user is logged in and can therefore view this page, however, this particular user is the CREATOR of this event. Therefore, on this event's show page, users who have been invited are allowed to view it, and so is the event creator, but only the event creator will see a button that when clicked, does a delete request to the event. The other users will not see this button.

The only way I see this being possible is that the JWT containing the user object can be decoded on the front/end, then I have access to variables with the decoded JWT properties. I.E., username and userID. That way, on the view page being rendered in Angular, I can code logic such as: ```

if (decodedJWT.user.username === event.creator.username) {
 DO SOMETHING HERE LIKE DISPLAY A CERTAIN BUTTON
}

```

Thanks.

Upvotes: 1

Views: 113

Answers (1)

gyc
gyc

Reputation: 4360

You need to create an API point in your nodeJS backend that will return the user details if he is logged in:

app.use('/userinfo', expressJwt({secret: secret}));

Here you make sure /userinfo is protected by JWT and your secret phrase.

Then the route corresponding to this API returns user info:

router.get('/get', function (request, response) {
  response.json({
    id: request.user.id,
    name: request.user.nom,
    email: request.user.email,
    role: request.user.role
  });
});

The full API is located at /userinfo/get and is secured by the JWT token.

In angularJS you just need to make a request to that API using simple $http.get('/userinfo/get') which will return a user object or an error from the server if not logged in.

Of course you need to pass the token to all your $http requests.

Upvotes: 0

Related Questions