javascript - 如何给被视作为静态资源的spa加上csrf保护?

 梦一直在延续 发布于 2022-11-29 15:51

最近我在使用react+react-router开发spa,后台使用的是yii2nignx设置的是当404就返回index.html。但是这样子有个问题是,我没有办法使用csrf的保护,这样子要怎么解决呢?

我看到了一个网站使用的技术栈和我的差不多,我看了它是在head标签上面写了一个含有token值的meta标签,而它的每一个请求都会将这个token作为header的值发回去。这样子要怎么做?要怎么将token值渲染到这个index.html里头?

1 个回答
  • ajax提交的

    $.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('等待回调');},})

    将输出部分放在header头里

    <?php//+----------------------------------------------------------------------//|CSRF安全验证类@pushaowei//+----------------------------------------------------------------------//|[Usage]//|//后端//|uselibrary\Base\NoCSRF;//|session_start();//|if($this->getRequest()->isPost()){//|//|try{//|##验证TOKEN//|NoCSRF::check('csrf_token',$_POST,true,60*10,false);//60*10为10分钟(null为不验证时间)//|$result='CSRFcheckpassed.Formparsed.';//|//$this->getRequest()->getPost('field');//|echo$result;//|}catch(Exception$e){//|echo$e->getMessage().'Formignored.';//|}//|}else{//|#生成TOKEN//|$token=NoCSRF::generate('csrf_token');//|$this->getView()->assign('token',$token);//|$this->getView()->display('页面');//|}//|//前端//|<metaname="csrf-token"content="<?phpecholibrary\Base\NoCSRF::generate('csrf_token');?>"/>//+----------------------------------------------------------------------classNoCSRF{protectedstatic$doOriginCheck=false;/***CheckCSRFtokensmatchbetweensessionand$origin.*Makesureyougeneratedatokenintheformbeforecheckingit.**@paramString$keyThesessionand$originkeywheretofindthetoken.*@paramMixed$originTheobject/associativearraytoretreivethetokendatafrom(usually$_POST).*@paramBoolean$throwException(Facultative)TRUEtothrowexceptiononcheckfail,FALSEordefaulttoreturnfalse.*@paramInteger$timespan(Facultative)Makesthetokenexpireafter$timespanseconds.(null=never)*@paramBoolean$multiple(Facultative)Makesthetokenreusableandnotone-time.(Usefulforajax-heavyrequests).**@returnBooleanReturnsFALSEifaCSRFattackisdetected,TRUEotherwise.*/publicstaticfunctioncheck($key,$origin,$throwException=false,$timespan=null,$multiple=false){$session=Session::getInstance();if(!$session->has('csrf_'.$key))if($throwException)thrownew\Exception('MissingCSRFsessiontoken.');elsereturnfalse;if(!isset($origin[$key]))if($throwException)thrownew\Exception('MissingCSRFformtoken.');elsereturnfalse;//Getvalidtokenfromsession$hash=$session->get('csrf_'.$key);//Freeupsessiontokenforone-timeCSRFtokenusage.if(!$multiple)$session->forget('csrf_'.$key);//Originchecksif(self::$doOriginCheck&&sha1($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT'])!=substr(base64_decode($hash),10,40)){if($throwException)thrownew\Exception('Formorigindoesnotmatchtokenorigin.');elsereturnfalse;}//Checkifsessiontokenmatchesformtokenif($origin[$key]!=$hash)if($throwException)thrownew\Exception('InvalidCSRFtoken.');elsereturnfalse;//Checkfortokenexpirationif($timespan!=null&&is_int($timespan)&&intval(substr(base64_decode($hash),0,10))+$timespan<time())if($throwException)thrownew\Exception('CSRFtokenhasexpired.');elsereturnfalse;returntrue;}/***Addsextrauseragentandremote_addrcheckstoCSRFprotections.*/publicstaticfunctionenableOriginCheck(){self::$doOriginCheck=true;}/***CSRFtokengenerationmethod.Aftergeneratingthetoken,putitinsideahiddenformfieldnamed$key.**@paramString$keyThesessionkeywherethetokenwillbestored.(Willalsobethenameofthehiddenfieldname)*@returnStringThegenerated,base64encodedtoken.*/publicstaticfunctiongenerate($key){$session=Session::getInstance();$extra=self::$doOriginCheck?sha1($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']):'';//tokengeneration(basicallybase64_encodeanyrandomcomplexstring,time()isusedfortokenexpiration)$token=base64_encode(time().$extra.self::randomString(32));//storetheone-timetokeninsession$session->put('csrf_'.$key,$token);return$token;}/***Generatesarandomstringofgiven$length.**@paramInteger$lengthThestringlength.*@returnStringTherandomlygeneratedstring.*/protectedstaticfunctionrandomString($length){$seed='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijqlmnopqrtsuvwxyz0123456789';$max=strlen($seed)-1;$string='';for($i=0;$i<$length;++$i)$string.=$seed{intval(mt_rand(0.0,$max))};return$string;}}?>
    2022-11-29 17:54 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有