简体   繁体   English

Angular和PHP JWT和CSRF(XSRF)Cookies

[英]Angular and PHP JWT and CSRF (XSRF) Cookies

I have an Angular app making $http requests to a PHP server. 我有一个向$ PHP服务器发出$ http请求的Angular应用程序。 Once a valid login request has been submitted to the server, PHP creates a JWT and sets the token cookie using PHP's setcookie() function with the httponly flag set to true. 将有效的登录请求提交给服务器后,PHP将创建一个JWT,并使用PHP的setcookie()函数(将httponly标志设置为true)来设置令牌cookie。 This flag allows only the server to read the cookie. 该标志仅允许服务器读取cookie。 On each subsequent Angular $http request, the cookie is validated by PHP using $_COOKIE. 在每个后续的Angular $ http请求中,cookie都由PHP使用$ _COOKIE进行验证。

My question is would setting the cookie in PHP for only the server to read be safe enough from CSRF or would I need to have Angular create an additional XSRF token to be sent on each request to be evaluated as well? 我的问题是在PHP中将cookie设置为仅用于从CSRF读取的服务器是否足够安全,还是我需要让Angular创建一个额外的XSRF令牌以在每个要评估的请求上发送呢?

I read the following Stormpath article but got a little lost on why he was setting a xsrfToken in the JWT payload. 我阅读了以下Stormpath文章,但对他为何在JWT有效负载中设置xsrfToken感到有些困惑。 My guess was to have Angular create an XSRF token to match against. 我的猜测是让Angular创建一个XSRF令牌进行匹配。

Thanks for any advice/input. 感谢您的任何建议/意见。

CSRF attacks work by exploiting the fact that your authentication cookie is sent by the browser to the server automatically with each request. CSRF攻击通过利用身份验证cookie随浏览器自动随每个请求发送到服务器这一事实而起作用。 Normally, a JWT isn't passed to the server using a cookie, it's instead passed in the authentication header of your http request (it may be stored in a cookie on the client side but the cookie isn't used to pass the JWT to the server). 通常,JWT不会使用cookie传递到服务器,而是传递到您的http请求的身份验证标头中(它可能存储在客户端的cookie中,但是cookie并不用于将JWT传递给服务器)。 Since you need to set the authentication header for each request, a CSRF attack cannot authenticate its malicious request since the browser isn't automatically sending an authentication cookie with each request. 由于您需要为每个请求设置身份验证标头,因此CSRF攻击无法对恶意请求进行身份验证,因为浏览器不会随每个请求自动发送身份验证cookie。 This is why JWTs help prevent CSRF attacks. 这就是JWT帮助防止CSRF攻击的原因。

That said, if you store your JWT in a cookie and transfer the cookie back and forth, extracting the token to check authorization policies, then you are just as susceptible to CSRF attaks as standard cookie authentication. 就是说,如果您将JWT存储在cookie中,并来回传输cookie,提取令牌以检查授权策略,那么您就像标准cookie身份验证一样容易受到CSRF攻击。 In this case you can add anti-forgery tokens to your requests to ensure that any HTTP requests that your server receives have come directly from your website. 在这种情况下,您可以在请求中添加防伪令牌,以确保服务器收到的任何HTTP请求都直接来自您的网站。

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

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