检查ajax请求是否已通过身份验证的中间件不起作用 [英] Middleware to check if ajax request is authenticated is not working

查看:45
本文介绍了检查ajax请求是否已通过身份验证的中间件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理从空闲/过期会话发起的ajax请求(也许页面保持打开状态并且会话已过期).我写了下面的中间件,但是没有按预期工作:

I am trying to handle ajax request that were initiated from idle/expired session(maybe the page was left open and the session got expired). I wrote the below middleware but it's not working as expected:

namespace App\Http\Middleware;

use Closure;

class AjaxSessionCheck
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
    public function handle($request, Closure $next)
    {
        if(!\Auth::check())
        {
            if($request->ajax())
            {
                return response()->json(['Session_error'=>'Session Expired'], 401);
                //throw new AuthenticationException('Unauthenticated');
            }
        }

        return $next($request);
    }
}

要检查此方法是否有效,我从两个单独的选项卡登录到包含表单的同一页面,然后从一个选项卡中注销,从而使会话在另一个选项卡上也无效.然后,我发起了一个ajax请求(用户单击删除按钮).

To check if this worked i logged into the same page that contains the form from two separate tabs and then logged out from one of the tab, making the session invalid on the other tab as well. Then i initiated an ajax request(user clicks a delete button).

任何对正确方向的帮助将不胜感激!

Any help to the right direction will be much appreciated!

推荐答案

为获得更好的覆盖范围,请使用if ($request->isJson() || $request->wantsJson()) {

for better coverage use if ($request->isJson() || $request->wantsJson()) {

这篇关于检查ajax请求是否已通过身份验证的中间件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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