Javascript-how to add csrf protection to the spa that is regarded as a static resource?

Source: Internet
Author: User
Tags csrf attack
Recently I am using react + react-router to develop a spa, and yii2 is used in the background. You can set the default value to index.html. However, the problem is that I cannot use csrf protection. how can this problem be solved? I saw a technology stack used by a website and my... recently I am using react+ react-routerDevelopment SpaThe background uses yii2. nignxWhen 404Returns index.html. But the problem is that I cannot use it. csrfHow can this problem be solved?

I saw a technology stack used by a website that is similar to mine. I saw that it includedtokenValue meta tag, and each request willtokenAsheader. How can we do this? HowtokenThe value is rendered to thisindex.htmlInside?

Reply content:

Recently I am usingreact+react-routerDevelopmentSpaThe background usesyii2.nignxWhen404Returnsindex.html. But the problem is that I cannot use it.csrfHow can this problem be solved?

I saw a technology stack used by a website that is similar to mine. I saw that it includedtokenValue meta tag, and each request willtokenAsheader. How can we do this? HowtokenThe value is rendered to thisindex.htmlInside?

Submitted by ajax

$. Ajax ({url: your urltype: by which dataType: data type data: headers: {'X-CSRF-TOKEN ': $ ('meta [name = "csrf-token"] '). attr ('content ')? $ ('Meta [name = "csrf-token"] '). attr ('content'): ''}, beforeSend: function (msg) {alert ('wait for callback ');},})

Place the output part in the header


  GetRequest ()-> isPost () {// | try {// | # verify TOKEN // | NoCSRF: check ('csrf _ token ', $ _ POST, true, 60*10, false); // 60*10 is 10 minutes (null is not the verification time) // | $ result = 'csrf check passed. form parsed. '; // | // $ this-> getRequest ()-> getPost ('field'); // | echo $ result; // |} catch (Exception $ e) {// | echo $ e-> getMessage (). 'form ignored. '; // |} else {// | # generate TOKEN // | $ token = NoCSRF: generate ('csrf _ token '); // | $ this-> getView ()-> assign ('token', $ token); // | $ this-> getView () -> display ('page'); // |} // | // front-end // |
  // + Define class NoCSRF {protected static $ doOriginCheck = false;/*** Check CSRF tokens match between session and $ origin. * Make sure you generated a token in the form before checking it. ** @ param String $ key The session and $ origin key where to find the token. * @ param Mixed $ origin The object/associative array to retreive the tok En data from (usually $ _ POST ). * @ param Boolean $ throwException (Facultative) TRUE to throw exception on check fail, FALSE or default to return false. * @ param Integer $ timespan (Facultative) Makes the token expire after $ timespan seconds. (null = never) * @ param Boolean $ multiple (Facultative) Makes the token reusable and not one-time. (Useful for ajax-heavy requests ). ** @ return Boolean Returns FALSE if a CSRF attack is detected, TRUE otherwise. */public static function check ($ key, $ origin, $ throwException = false, $ timespan = null, $ multiple = false) {$ session = Session: getInstance (); if (! $ Session-> has ('csrf _'. $ key) if ($ throwException) throw new \ Exception ('missing CSRF session token. '); else return false; if (! Isset ($ origin [$ key]) if ($ throwException) throw new \ Exception ('missing CSRF form token. '); else return false; // Get valid token from session $ hash = $ session-> get ('csrf _'. $ key); // Free up session token for one-time CSRF token usage. if (! $ Multiple) $ session-> forget ('csrf _'. $ key); // Origin checks if (self: $ doOriginCheck & sha1 ($ _ SERVER ['remote _ ADDR ']. $ _ SERVER ['http _ USER_AGENT '])! = Substr (base64_decode ($ hash), 10, 40) {if ($ throwException) throw new \ Exception ('form origin does not match token origin. '); else return false;} // Check if session token matches form token if ($ origin [$ key]! = $ Hash) if ($ throwException) throw new \ Exception ('invalid CSRF token. '); else return false; // Check for token expiration if ($ timespan! = Null & is_int ($ timespan) & intval (substr (base64_decode ($ hash), 0, 10) + $ timespan <time () if ($ throwException) throw new \ Exception ('csrf token has expired. '); else return false; return true;}/*** Adds extra useragent and remote_addr checks to CSRF protections. */public static function enableOriginCheck () {self: $ doOriginCheck = true;}/*** CSRF token generation method. afte R generating the token, put it inside a hidden form field named $ key. ** @ param String $ key The session key where the token will be stored. (Will also be the name of the hidden field name) * @ return String The generated, base64 encoded token. */public static function generate ($ key) {$ session = Session: getInstance (); $ extra = self: $ doOriginCheck? Sha1 ($ _ SERVER ['remote _ ADDR ']. $ _ SERVER ['http _ USER_AGENT ']): ''; // token generation (basically base64_encode any random complex string, time () is used for token expiration) $ token = base64_encode (time (). $ extra. self: randomString (32); // store the one-time token in session $ session-> put ('csrf _'. $ key, $ token); return $ token;}/*** Generates a random string of given $ length. ** @ par Am Integer $ length The string length. * @ return String The randomly generated string. */protected static function randomString ($ length) {$ seed = 'hangzhou'; $ max = strlen ($ seed)-1; $ string = ''; for ($ I = 0; $ I <$ length; ++ $ I) $ string. =$ seed {intval (mt_rand (0.0, $ max) }; return $ string ;}}?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.