JavaScript-How to add csrf protection to a spa that is viewed as a static resource?

Source: Internet
Author: User
Tags sha1 throw exception csrf attack
Recently I was using react+ react-routerDevelopment Spa, the background is using yii2nignxSet is when the 404will return index.html。 But there's a problem with that, I can't use it. csrfprotection, how to solve this?

I saw a Web site using a technology stack like mine, I saw it was a meta tag with a value written on the head tag token , and every request would token header send the value back. How do you do that? How do you token render the value into this index.html ?

Reply content:

Recently I was using react + react-router Development Spa, which is used in the background yii2 . nignxis set to 404 return when it is index.html . But there is a problem with this, I have no way csrf to use the protection, how to solve it?

I saw a Web site using a technology stack like mine, I saw it was a meta tag with a value written on the head tag token , and every request would token header send the value back. How do you do that? How do you token render the value into this index.html ?

Ajax-Submitted

$.ajax({url: 你的urltype:依什么方式dataType:数据类型data :headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') ? $('meta[name="csrf-token"]').attr('content') : ''},beforeSend:function(msg){alert('等待回调');},})

Place the output part in the header


  Getrequest ()->ispost ()) {//|        // |            try {//|            # #验证TOKEN//| Nocsrf::check (' Csrf_token ', $_post, True, 60*10, false);            60*10 for 10 minutes (null for no Authentication time)//| $result = ' CSRF check passed. Form parsed. ';            / |            $this->getrequest ()->getpost (' field ');//|       echo $result;        // |            } catch (Exception $e) {//| echo $e->getmessage (). ' Form ignored. ';        // |    }      // |        } else {//|        #生成TOKEN//|        $token = nocsrf::generate (' Csrf_token ');//|        $this->getview ()->assign (' token ', $token);//|    $this->getview ()->display (' page ');//|    }// | Front-end//|
  
   
  +----------------------------------------------------------------------class nocsrf{protected static $    Doorigincheck = false;      /** * Check CSRF tokens match between session and $origin.     * Make sure generated a tokens 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 token 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 CS            RF session token. ');                    else return false; if (!isset ($origin [$key])) if ($throwException) throw new \exception (' Missing CSRF form to            Ken. ');        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), ten, +)) {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 ($throwE            xception) throw new \exception (' Invalid CSRF token. ');        else return false; Check for token expiration if ($timespan! = null && is_int ($timespan) && intval (substr (base 64_decode ($hash), 0,) + $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.     After generating the token, put it inside a hidden form field named $key. * * @param String $key The session key where the token would be stored. (would 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 () was used for token expiration) $toke        n = 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.     * * @param Integer $length the string length.     * @return string the randomly generated string. */protected static function RandomString ($length) {$seed = ' abcdefghijklmnopqrstuvwxyzabcdefghijqlmnopqrt        suvwxyz0123456789 ';        $max = strlen ($seed)-1;        $string = "; for ($i = 0; $i < $length;        + + $i) $string. = $seed {intval (Mt_rand (0.0, $max))};    return $string; }}?>
  • Related Article

    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.