简体   繁体   English

如何通过反应进行 JWT 身份验证?

[英]How to do JWT authentication with react?

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.我不确定如何在前端正确进行 JWT 身份验证,但我在后端几乎没有任何问题。

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使用 Javascript 我并没有超出这个片段太远,因为我不得不重做很多次,但无论如何它都不起作用

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我只需要能够识别用户,他们的所有数据,例如个人资料信息,照片等......并且用户只能访问自己的数据

JWTs are used to encode what actions user is allowed to take and which pages to see. JWT 用于编码允许用户采取哪些操作以及查看哪些页面。 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.为了检索他们的数据,例如个人资料信息、照片等,您必须发送其他信息,可能是用户 ID,或者您必须在默认情况下不存在的令牌内对 id 字段进行编码。

You already have what you need.你已经拥有了你需要的东西。 the access&refresh tokens are the ones needed for routes that require authorization. access&refresh 令牌是需要授权的路由所需的令牌。 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 ->登录后,您将令牌保存在浏览器上,只要令牌有效,用户就已登录。令牌与需要授权才能访问的请求一起发送为 header 就像这样让我们说要获取用户完整配置文件已登录 ->

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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