Auth 过滤器重定向回 Laravel 中的原始 POST 请求

2023-12-27

看来 Redirect::guest('login') 只适用于 GET 请求。 IE。它会将经过身份验证的用户重定向到原始预期 URL (GET)。

在存在 POST 请求的情况下,是否有办法让身份验证过滤器在用户成功登录后继续 POST 到 URL?

一个简单的例子:我想显示一个可供任何人查看的表单。点击提交按钮后,身份验证过滤器将启动,将访客带到登录页面。身份验证成功后,我希望继续提交请求(即 POST 请求)。


我也有同样的愿望,希望使用原始输入重定向回 POST 请求。除了通过 GET 重定向到预期的 URL 之外,我在 Laravel 中找不到现有的方法来执行此操作。

拉拉维尔 5

我首先按照下面的大纲在 Laravel 4 中解决了这个问题,但发现完全相同的设置在 Laravel 5 中不起作用。按照 Laravel 4 的大纲,但不是创建 IntendedUrlServiceProvider,而是创建一个中间件。

  1. 问题是,在 Laravel 5 中,会话似乎是通过 StartSession 启动的,该 StartSession 在所有 ServiceProviders 之后运行。

/app/Http/Middleware/IntendedUrl.php

<?php namespace App\Http\Middleware;

use Closure;
use Request;
use Session;

class IntendedUrl {

    /**
     * This loads saved POST input data and changes the method to POST if a visitor tried to access a page
     * but was blocked via an auth filter. Auth filter saves data via the Redirect::guest() and after
     * login it needs to be repopulated to simulate a POST.
     *
     * GET requests also may pass through here. I am less certain if it is required for them but shouldn't hurt
     * and may help load any input data.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Check to see if we were redirected to this page with the Redirect::intended().
        //      We extended the class to track when the redirect occurs so we know to reload additional request data
        if (Session::has('intended.load')) {
            // intended.load could be set without these being set if we were redirected to the default page
            //      if either exists, both should exist but checking separately to be safe
            if (Session::has('intended.method')) {
                Request::setMethod(Session::get('intended.method'));
            }
            if (Session::has('intended.input')) {
                Request::replace(Session::get('intended.input'));
            }
            // Erase all session keys created to track the intended request
            Session::forget('intended');

            // Laravel 5.2+ uses separate global and route middlewares. Dispatch altered request as the route type changed. *Credit to Munsio in answer below
            return \Route::dispatch($request);
        }

        return $next($request);
    }

}
  1. 然后,不要像下面的步骤 4 中那样添加 IntendedUrlServiceProvider,而是在 /app/Http/Kernel.php 的 $middleware 数组中的 StartSession 之后添加新的中间件
protected $middleware = [
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',

    'App\Http\Middleware\IntendedUrl',
];
  • 另外值得注意的是,为了组织,我将我的客户服务提供商移至新标准 /App/Providers 并更改了他们的命名空间。

拉拉维尔 4

我决定扩展框架以添加此功能。很难详细说明我的完整解决方案,但这里有一个轮廓。为此,您需要非常熟悉该框架并阅读如何扩展它。http://laravel.com/docs/extending#ioc-based-extension http://laravel.com/docs/extending#ioc-based-extension

我还参考了 Taylor 的书《Laravel from Apprentice to Artisan》

  1. 扩展 Redirector 类以记录有关预期请求的附加信息。

    <?php namespace GQ\Routing;
    class Redirector extends \Illuminate\Routing\Redirector {
        /**
         * ** Extended to add functionality for restoring POST input and the POST method after a login
         */
        public function guest($path, $status = 302, $headers = array(), $secure = null)
        {
            // Recording the method and input for the request so that it can be reloaded after being redirected back to the intended page
            $this->session->put('intended.method', $this->generator->getRequest()->getMethod());
            $this->session->put('intended.input', $this->generator->getRequest()->all());
    
            return parent::guest($path, $status, $headers, $secure);
        }
    
        /**
         * ** Extended to record in the session when we redirect to an intended page so method and input can be loaded on the next page
         */
        public function intended($default = '/', $status = 302, $headers = array(), $secure = null)
        {
            $redirect_response = parent::intended($default, $status, $headers, $secure);
    
            // Set the intended.load session variable so we know we returned to the intended page and can load the additional method and input
            return $redirect_response->with('intended.load', true);
        }
    }
    ?>
    
  2. 创建一个新的服务提供者,覆盖 IOC 容器中的“重定向”。我最初尝试扩展 RoutingServiceProvider 但在工作时遇到了问题。

    <?php namespace App\Providers;
    
    use GQ\Routing\Redirector;
    use Illuminate\Support\ServiceProvider;
    class RedirectServiceProvider extends ServiceProvider {
    
        protected $defer = true;
    
        /**
         * Register the Redirector service.
         *
         * ** Copy of class registerRedirector from RoutingServiceProvider,
         * using a different "use" statement at the top to use the extended Redirector class
         * Extending the RoutingServiceProvider was more of a pain to do right since it is loaded as a base provider in the Application
         *
         * @return void
         */
        public function register()
        {
            $this->app['redirect'] = $this->app->share(function($app)
            {
                $redirector = new Redirector($app['url']);
    
                // If the session is set on the application instance, we'll inject it into
                // the redirector instance. This allows the redirect responses to allow
                // for the quite convenient "with" methods that flash to the session.
                if (isset($app['session.store']))
                {
                    $redirector->setSession($app['session.store']);
                }
    
                return $redirector;
            });
        }
        public function provides() {
            return array('redirect');
        }
    }
    
  3. 创建一个新的服务提供者,它将在重定向后设置预期的方法和输入。

    <?php
    
    namespace GQ\Providers;
    
    use Illuminate\Support\ServiceProvider;
    
    class IntendedUrlServiceProvider extends ServiceProvider {
        /**
         * Bootstrap the application events.
         *
         * @return void
         */
        public function boot() {
            // Check to see if we were redirected to this page with the Redirect::intended().
            //        We extended the class to track when the redirect occurs so we know to reload additional request data
            if (\Session::has('intended.load')) {
                // intended.load could be set without these being set if we were redirected to the default page
                //        if either exists, both should exist but checking separately to be safe
                if (\Session::has('intended.method')) {
                    \Request::setMethod(\Session::get('intended.method'));
                }
                if (\Session::has('intended.input')) {
                    \Request::replace(\Session::get('intended.input'));
                }
                // Erase all session keys created to track the intended request
                \Session::forget('intended');
            }
        }
    
        public function register() {
        }
    }
    
  4. 最后将 2 个新的服务提供者添加到 app/config/app.php 中的提供者数组中

    'GQ\Providers\RedirectServiceProvider',
    'GQ\Providers\IntendedUrlServiceProvider',
    

希望这能引导您朝着好的方向发展。这对我有用,但我没有对其进行广泛的测试。也许如果它继续运行良好,我们可以构建一个 Composer 包或获得 Laravel 中包含的功能。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Auth 过滤器重定向回 Laravel 中的原始 POST 请求 的相关文章

  • Laravel Mongo 多对多关系在哪里不起作用

    我有两个以多对多关系相互关联的 mongo 文档 一个称为律师 另一个称为律师 我的律师模型有 public function cases return this gt belongsToMany App LawCase 我的 LawCas
  • node npm run watch 退出状态 3221225725

    我必须格式化我的驱动器 但我的一个项目不再工作 所有其他相同类型的项目都运行良好 这是 Laravel Vue JS 问题是我无法运行 npm run watch dev 或 production 他们都给出了错误 拉拉维尔 5 7 npm
  • HttpHostConnectException:连接被拒绝 Android

    我正在尝试通过 HttpPost 连接并将用户名和密码发送到网站 然后从该网站接收字符串 我过去尝试过各种对我有用的方法 但现在当我发送用户名和密码标识符时 应用程序超时长达 4 分钟 然后抛出以下异常 07 16 16 32 32 897
  • 模型在自身内部调用自己是一种不好的做法吗?

    这是一个在 Laravel 中使用 Eloquent 的示例 假设我正在开发 CMS 控制器获取路由并通过路由查找页面 该模型提供了一个静态函数 该函数使用路由来找出它正在查找的行的 id 那么模型使用本身执行数据库查询并返回结果 控制器代
  • 请确保至少一个领域可以验证这些令牌

    所以我把我的shiro设置为有两个Realms 用户名和密码领域 使用标准 UsernamePasswordToken 我还设置了一个自定义承载身份验证令牌 用于处理从用户传入的令牌 如果我只使用我的passwordValidatorRea
  • Angular2 + Laravel 与实时和 WebSockets

    我构建了一个应用程序 并计划与 Angular 2 和 laravel 进行实时战斗 例如 你按下 攻击 按钮 你的对手就会实时看到他的生命在下降 我的应用程序构建有 前端 角2 Backend PHP Laravel 5 2 现在我正在寻
  • Laravel 5 - 更改默认日志位置,将日志文件移至应用程序之外

    如何更改默认日志文件位置
  • Firebase GAS webapp Google 弹出窗口消失

    我正在尝试升级我的 firebase GAS web 应用程序 之前我有一个弹出窗口 可以让用户使用 Google 登录 我不确定我做错了什么 但我已经升级到新的 firebase 现在正在尝试使用新的代码格式进行相同的登录 发生的情况是
  • 使用 Django REST 框架进行 SAML SSO 身份验证

    我目前正在开发 AngularJS 前端和 Django REST 后端 我一直在使用Django rest auth https github com Tivix django rest auth过去需要对两者之间的连接进行身份验证 但现
  • Laravel 集成测试:如何断言一个 URL 已被调用但另一个 URL 没有

    我想测试一个向某个 URL 发出请求的控制器 例如 http example com api say hello 但它不会向另一个 URL 发出请求 例如 http example com api say bye bye 我想测试的控制器功
  • MYSQL 区分大小写的 utf8 搜索(使用 hibernate)

    我的登录表具有 utf8 字符集和 utf8 排序规则 当我想要检查用户名并检索该特定用户名的其他信息时 hql 查询会为我提供小写和大写相同的结果 我应该如何处理适用于案例的 HQL 查询 我使用 Mysql 5 和 java hiber
  • HTTP:为什么在 get 请求中发送用户名和密码是错误的?

    一般做法是 当您登录或执行其他需要您的用户名和密码的操作时 您将其发送到发布请求的正文中 此外 为了增加安全性 应使用 https 在 get 请求中 这些参数作为 URL 的一部分发送 但据我了解 在 https 中 正文和标头都是加密的
  • 这个条带请求是什么?为什么它会多次触发?

    对于使用 stripe 的 Laravel 应用程序 此请求https r stripe com 0被解雇多次 如下所示 我刷新主页后 这些请求立即被触发 问题是我最近得到了一个429 too many requests我的实时服务器出现错
  • 使用 Apache HTTPd 模块的 OAuth 2.0 身份验证

    是否可以使用 Apache HTTPd 服务器模块来实现 OAuth 2 0 或 1 0 我选择这条路线是因为每个请求都会首先到达 HTTPd 模块 因此我必须从那里进行身份验证 如果可能的话 请分享相关链接 我要补充一下尤金尼奥的答案mo
  • 免费 PHP 登录库 [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • AWS-PHP-SDK / SNS 直接寻址返回错误

    您好 我正在使用 Laravel 4 设置来利用 AWS SNS 向我的 iOS 设备发送推送消息 从 AWS 控制台向我的设备发布命令效果很好 然后我尝试从 PHP sns AWS get sns sns gt publish array
  • CakePHP 身份验证插件身份关联

    我正在使用 CakePHP 3 8 并迁移到身份验证插件 https book cakephp org authentication 1 1 en index html https book cakephp org authenticati
  • Flask 会话变量

    我正在用 Flask 编写一个小型网络应用程序 当两个用户 在同一网络下 尝试使用应用程序时 我遇到会话变量问题 这是代码 import os from flask import Flask request render template
  • Laravel Vue 组件只能传递数字?

    在我的 UserMenu vue 中我写道 export default props nameVal data return 并在blade php中
  • Asp.net Identity 注销其他用户

    我正在使用 Asp net Identity 来验证用户身份 并尝试从管理端锁定任何用户 但是当我锁定任何在线用户时 它并没有注销 我读过很多关于我的问题的评论 但它们都不起作用 我尝试使用 UserManager UpdateSecuri

随机推荐

  • 如今何时使用定点

    对于密集的数字运算 我正在考虑使用定点而不是浮点 当然 定点类型的大小有多少字节 它将在什么 CPU 上运行 如果我可以使用 对于英特尔 MMX 或 SSE 或任何新出现的东西 这都很重要 我想知道现在浮点运行速度比以往任何时候都快 是否值
  • Android MediaCodec:编码失败,因为视频轨道没有同步帧

    我计划将一个视频文件转换为另一个具有不同比特率 fps 等的视频文件 基本上我遵循中的示例http bigflake com mediacodec http bigflake com mediacodec 但是 日志显示视频轨道没有同步帧的
  • Heroku:“https://git.heroku.com”的用户名:git

    我正在尝试检查 heroku 上的 git 远程 heroku auth logout Local credentials cleared heroku auth login Enter your Heroku credentials Em
  • 如何查找特定 Subversion 用户所做的修订?

    使用命令行 我想查看特定用户所做的所有更改集 这可能吗 我查看了文档svn log但不知道如何做到这一点 我不知道有什么方法可以使用纯 Subversion 来做到这一点 但你可以做到with sed http svn haxx se us
  • PHP - preg_replace - 文本链接作为可点击链接

    我使用此 preg replace 将文本 url 更改为可在脚本中单击 将文本链接替换为带有 preg replace 的链接 https stackoverflow com questions 13105960 replacing te
  • jQuery element.data() 语法。我怎么知道`$(this)`是什么?

    我有以下 jQuery 变量 var confirmbox div div data defaultText This action cannot be reversed Are you sure you wish to do this d
  • intellij idea中设置tomcat的问题

    我正在尝试使用 intellij idea 创建一个简单的测试 Restful Web 服务 我正在关注这个教程 https medium com jamsesso starting out with jersey apache tomca
  • 当您克隆 Backbone.Collection 时,模型引用是否完好无损?

    我正在 clone ing 一个集合 以便我可以在其上使用拼接循环而不干扰原始集合 克隆阵列中的模型是原件还是副本 我需要的是包含原始模型的数组的副本 感谢您提供任何信息 您将获得与包装在相同类型的新集合中的源集合相同的模型 这是colle
  • 拖动元素时滚动 div 而不移动鼠标

    我开发了一个代码 其中包括一个表格 其中所有单元格都是可删除的 表格容器是具有固定高度和滚动条的 div 我想将一个元素 在我的示例中为黄色方块 拖到表格底部的最后一个表格单元格中 一切正常 但要在拖动元素时激活 div 容器的滚动条 我必
  • 如何绑定到 Style.Resource 中的附加属性?

    我正在尝试使用附加属性在 TextBox 的背景中创建提示文本标签 但无法解析样式资源中文本标题的绑定 风格定义
  • Postgres 数据库已锁定:查询永远运行

    我的一个 python 脚本在 Postgres 数据库上运行了一些 ALTER TABLE 查询 发生了一些问题 桌子被锁了 当我对这些表中的任何一个运行任何查询时 它告诉我查询正在运行 但什么也没有发生 目前 我只能通过关闭系统并重新启
  • iOS 5.0 用户代理字符串是什么?

    是什么iOS 5 0用户代理字符串 这里是iOS 4 0用户代理 iPhone 4 用户代理是什么 https stackoverflow com q 3105555 836407 iPhone Mozilla 5 0 iPhone CPU
  • KIF 输出:AX Exchange 错误:错误域=辅助功能代码=0“远程服务不响应 _accessibilityMachPort”

    在使用 iOS 8 1 3 的设备上运行 KIF 集成测试时 我收到大量以下类型的诊断消息作为控制台输出 AX Exchange 错误 错误域 辅助功能代码 0 远程服务 不响应 accessibilityMachPort UserInfo
  • 将文件读入数组 - Java

    我正在练习java 并在网上查看练习 然而 我陷入了我需要的地步 Read the file again and initialise the elements of the array Task 将表示成员列表的类 Members 编写为
  • file_exists() 的 PHP 不区分大小写版本

    我试图想出在 PHP 中实现不区分大小写的 file exists 函数的最快方法 我最好的选择是枚举目录中的文件并进行 strtolower 与 strtolower 比较 直到找到匹配项 我使用评论中的源代码来创建这个函数 如果找到则返
  • Firebase Auth UI 的电子邮件验证

    我在用firebase auth UI FirebaseUI Android https github com firebase FirebaseUI Android blob master auth README md 在 Android
  • django 迁移 - 具有多个开发分支的工作流程

    我很好奇其他 django 开发人员如何通过迁移来管理多个代码分支 例如在 git 中 我的问题如下 我们在 git 中有多个功能分支 其中一些带有 django 迁移 其中一些更改字段 或完全删除它们 当我切换分支时 git checko
  • 将 jQuery 与 SQL Server 数据库连接

    我正在尝试构建一个 jQuery 功能 其场景如下所示 假设用户单击网站中的图像 页面上会弹出一个 jQuery 对话框 该对话框有一个文本字段 用于输入图像的 替代文本 当用户单击提交按钮时 该页面的文本应与图像的 URL 一起保存到我的
  • Hive 日期/时间戳列

    我在 HDFS 上有一些数据 我正在尝试将其设置为通过 hive 进行查询 数据采用逗号分隔文本文件的形式 文件中的一列是日期 时间列 如下所示 Wed Aug 29 16 16 58 CDT 2018 当我尝试读取使用以下脚本创建的 Hi
  • Auth 过滤器重定向回 Laravel 中的原始 POST 请求

    看来 Redirect guest login 只适用于 GET 请求 IE 它会将经过身份验证的用户重定向到原始预期 URL GET 在存在 POST 请求的情况下 是否有办法让身份验证过滤器在用户成功登录后继续 POST 到 URL 一