Home > Back-end >  What I'm doing wrong with this JWT authentication?
What I'm doing wrong with this JWT authentication?

Time:06-16

I'm not sure how to properly do JWT authentication on the front end, I didn't have almost any problems on the back end though.

with Javascript I didn't get too far past this snippet as I had to redo stuff many times and it didn't work anyway

const submit = async (e) => {
    e.preventDefault();
    await axios('http://localhost:8080/api/login', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        credentials: 'include',
        data:new URLSearchParams(`username=${username}&password=${password}`)
    });
}

Which basically just displays the access&refresh tokens in the network info of the page.

how do I actually identify the user on a website from there on and actually be able to use the user's own data, such as files for example?

I need to just be able to identify the user, all their data, such profile-info, photos etc... and the user to only be able to access its own data

CodePudding user response:

JWTs are used to encode what actions user is allowed to take and which pages to see. For example you could encode their role inside the token to indicate what they are allowed to access. In order to retrieve their data such as profile info, photos etc. you have to either send additional information, probably the user id or you have to encode the id field inside the token which is not there by default.

CodePudding user response:

You already have what you need. the access&refresh tokens are the ones needed for routes that require authorization. The token has the user details which identifies them to the back end who is making requests. after login you save the token on the browser and as long as the token is valid the user is logged in. The token are sent along with requests that need authorization to access as a header like this let say to get user full profile we need to have been logged in ->

axios(' api/user/profile ', { method: 'POST', headers: {'Content-Type': 'application/json,'Authorization':'Bearer' localStorage.getItem('user-token')}, });.

  • Related