简体   繁体   English

在 React 应用程序中使用访问令牌实现身份验证的最佳方法是什么?

[英]What could be the best way to implement authentication using access token in React app?

I am a newbie to React.我是 React 的新手。 Trying to implement authentication using Express.js in react web application.尝试在反应 web 应用程序中使用 Express.js 实现身份验证。 I have set token in response cookies on backend with HttpOnly flag but unable to read it on front end(react app).我已经在后端使用 HttpOnly 标志设置了响应 cookies 的令牌,但无法在前端读取它(反应应用程序)。 I have been through several tutorials of cookies and understood that it won't be readable in Javascript if it is HttpOnly.我已经阅读了 cookies 的几个教程,并且了解到如果它是 HttpOnly,它在 Javascript 中将无法读取。

I thought of creating cookies on React app but they will be non-HttpOnly which would make my website vulnerable.我想在 React 应用程序上创建 cookies 但它们将是非 HttpOnly ,这会使我的网站易受攻击。 What would be the best way to implement authentication in React app using access token?使用访问令牌在 React 应用程序中实现身份验证的最佳方法是什么?

I have set cookies using max-age, secure, and domain but unable to access cookies with HttpOnly flag in React app and setting cookies in React app won't make them HttpOnly.我已经使用 max-age、secure 和 domain 设置了 cookies,但无法在 React 应用程序中使用 HttpOnly 标志访问 cookies 并在 React 应用程序中设置 cookies 不会让它们。

We don't need to store or pass the token;我们不需要存储或传递令牌; we don't even have access to it from JavaScript because it's stored in an HttpOnly cookie.我们甚至无法从 JavaScript 访问它,因为它存储在 HttpOnly cookie 中。

Instead of readign the access token from server side response, use your server side code to set the cookie when its sending the response.与其从服务器端响应读取访问令牌,不如在发送响应时使用服务器端代码设置 cookie。 Use axios and The withCredentials property indicates to Axios that it should send the cookie for the API domain along with the request.使用 axios 和 withCredentials 属性向 Axios 指示它应该将 API 域的 cookie 与请求一起发送。 Ref: https://www.bignerdranch.com/blog/react-data-layer-part-3-login/参考: https://www.bignerdranch.com/blog/react-data-layer-part-3-login/

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

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