简单的后端生成令牌,前端获取,然后ajax设置header标头,后端进行对比

在 Web 应用中实现令牌失效(Token Expiration)通常涉及到两个方面:客户端的令牌使用和服务器端的令牌验证

<html>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
    <title>javascript设置自定义的标头获取数据</title>
    <body>
    <?php 
    //生成令牌,这里是直接写在这里做测试,你也可以单独写成函数或类,要用时再调用
    session_start();
    if(empty($_SESSION['csrf_token']))
        {
            $_SESSION['csrf_token']=bin2hex(random_bytes(32));
        }
    ?>
    //发送header头的按钮
        <button id="sendRequest">发送标头</button>
        
        <script type="text/javascript">
            document.getElementById("sendRequest").addEventListener("click",function(){
                let xhr=new XMLHttpRequest();
                //获取到session中的令牌信息,这一句在只php为后缀的页面中才能有效,不能用html为后缀
                let csrfToken = <?php echo json_encode($_SESSION['csrf_token']); ?>;
                console.log(csrfToken);
                //后端处理令牌信息和比对
                xhr.open('get',"headerapi.php");
				//设置标头,把令牌信息设置到标头中,然后发送到后端,对比也是在后端
                xhr.setRequestHeader('X-Custom-Header',csrfToken);
                xhr.responseType="json";
                //加载xhr,监控数据和标头是否被发送
                xhr.onload=function(){
                    if(xhr.status>=200 && xhr.status<300)
                    {
                        console.log('Request Data:',xhr.response);
                        //获取标头信息,这里获取标头只是演式令牌和标头令牌是否一致
                        let customresponseHeader=xhr.getResponseHeader("X-Custom-Response-Header");
                        let Ref=xhr.getAllResponseHeaders();
                        
                        if(csrfToken===customresponseHeader)
                        {
                            console.log('当前的标头:',customresponseHeader);
                        }
                        
                    }else
                    {
                        console.error('获取失败:',xhr.status);
                    }
                };
                xhr.onerror=function(){
                    console.log('连接时失败');
                };
                xhr.send();
            })
        </script>
    </body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值