如何在Laravel中为每个用户请求生成新的CSRF令牌? [英] How to generate new CSRF Token for each user request in Laravel?

查看:299
本文介绍了如何在Laravel中为每个用户请求生成新的CSRF令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为每个请求用户生成新的CSRF令牌.我确实知道此技术不好,并且不允许用户同时发出请求.但是我仍然希望实现它.

Im suppose to generate new CSRF token for each request user make. I do understand this technique is not good and it wont allow user to make simultaneous request. But still I wish to implement it.

我在 Middleware/VerifyCsrfToken 中具有覆盖功能 addCookieToResponse .通过添加 $ request-> session()-> regenerateToken().

I have override function addCookieToResponse in Middleware/VerifyCsrfToken. By adding $request->session()->regenerateToken().

protected function addCookieToResponse($request, $response)
{
    $config = config('session');
    $request->session()->regenerateToken();

    $response->headers->setCookie(
        new Cookie(
            'XSRF-TOKEN', $request->session()->token(), $this->availableAt(60 * $config['lifetime']),
            $config['path'], $config['domain'], $config['secure'], $config['http_only'], false, $config['same_site'] ?? null
        )
    );

    return $response;
}

令牌不断变化,但是在POST请求期间,由于 csrf_token()令牌过旧,我收到TokenMismatchExcemption.似乎在addCookieToResponse()之前调用了crsf_token().有没有更好的方法来实现这项技术?

The token keep changing but during POST request I receive TokenMismatchExcemption due to csrf_token() token to be old.It seems crsf_token() is called before addCookieToResponse(). Is there any better way to implement this technique?

推荐答案

您想要实现的目标有点怪异,但我像一个中间件那样思考:

Well its a bit weird what you're trying to achieve but i think about this like an after middleware:

$response = $next($request); // process petition

$request->session()->regenerateToken(); // regenerate token

return $response; // send response

请分享结果

这篇关于如何在Laravel中为每个用户请求生成新的CSRF令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆