反应前端和 RESTAPI,CSRF

在前端使用 React 和 RESTful API 作为后端,并通过 JSON Web 令牌(JWT)进行授权,我们如何处理会话?例如,在登录之后,我从 REST 获得一个 JWT 令牌。如果我把它保存到 localStorage,我就容易受到 XSS 的攻击,如果我把它保存到 Cookies,同样的问题,除了我把 Cookies 设置为 HttpOnly,但 React 不能读取 HttpOnly Cookies (我需要读取 cookie 从中获取 JWT,并使用这个 JWT 与 REST 请求) ,我也没有提到跨站点请求伪造(CSRF)问题。如果使用 REST 作为后端,则不能使用 CSRF 令牌。

因此,使用 REST 进行反应似乎是一个糟糕的解决方案,我需要重新考虑我的体系结构。是否有可能为您的用户提供一个安全的 React 应用程序,该应用程序在 REST API 端处理所有业务逻辑,而不用担心丢失数据?

更新:

据我所知,这是可能的:

  1. React 对 REST API 进行 AJAX 调用
  2. React 从 RESTAPI 获取 JWT 令牌
  3. React 写入 HttpOnly cookie
  4. 因为 React 不能读取 HttpOnly cookie,所以我们在所有需要身份验证的 REST 调用中使用它
  5. RESTAPI 调用检查 XMLHttpRequest 头,这是某种 CSRF 保护
  6. RESTAPI 端检查 cookie,从中读取 JWT 并执行操作

我缺乏理论知识。逻辑看起来相当安全,但我仍然需要一个答案,我的问题,并批准这个“工作流”。

72779 次浏览
  1. React makes AJAX call to REST API

assured, lots of restful resource client lib available

  1. React gets JWT token from REST

assured, this is what JWT should do

  1. React writes httponly cookie

I don't think so, It should not work, but session is not such a important thing, it'll soon get out of date, and recheck password on key operations, even the hackers got it in a very short time, you can bind session token together with IP when user login and check it in your backend apis. If you want it most secured, just keep token in memory, and redo login when open new page or page refreshes

  1. Because react can't read httponly cookie, we use it as-is in our all REST call where we need authentication

assured, check user and permissions through login token, like csrf you can put your login token into your request header, and check it in your backend apis. Bind login token to your own restful lib will save you a lot codes

  1. REST on calls checks XMLHttpRequest header, what is some kind of CSRF protection REST side check for cookie, read JWT from it and do stuff

assured, as most people do. Also, bind csrf token to your own restful lib will save you a lot codes

use user token in header https://www.npmjs.com/package/express-jwt-token Authorization JWT < jwt token >

use csrf token in header https://github.com/expressjs/csurf req.headers['csrf-token'] - the CSRF-Token HTTP request header.

restful client https://github.com/cujojs/rest

react with jwt https://github.com/joshgeller/react-redux-jwt-auth-example

Your server can set the JWT cookie directly as a response to the login request.

The server responds to POST /login with Set-Cookie: JWT=xxxxxx. That cookie is http only and therefore not vulnerable to XSS, and will be automatically included on all fetch requests from the client (as long as you use withCredentials: true).

CSRF is mitigated as you mentioned, see OWASP for details.