Route Filters「建议收藏」

Route Filters「建议收藏」RouteFiltersTheController’sMiddleware,representsaHigh-LevelprocessingAPI,executedbytherequestedController,whenitisinstantiated,itsrequestedMethodisknownasbeingvalidandca…

大家好,又见面了,我是你们的朋友全栈君。

Route Filters

The Controller’s Middleware, represents a High-Level processing API, executed by the requested Controller, when it is instantiated, its requested Method is known as being valid and callable, and working in the same flow as your wanted Method.

The graph of The Controller Execution Flow is as follow:

before() -> action() -> after()

While very efficient and accurate, sometimes this design is not the best. For example, to instantiate a Controller and start its Execution Flow, only to obtain a redirect from a CSRF fault, can be costly as resources and response speed.

Better is to have a solution for Routing to handle the CSRF fault, before to even instantiate the requested Controller, right after the Route was identified; this was the used resources will be lower and response speed will be better.

Enter the Route Filters: a method to execute specified callbacks right after the correct Route was identified and before starting the execution of associated Controller.

Route Filters

How do they work? Let’s say that we want a CSRF filter. In the (new) file app/Filters.php we define it as following:

Route::filter('csrf', function($route) { if (! Csrf::isTokenValid()) { return Redirect::to(''); } });

We’ll see that a Route Filter definition have a name as first parameter and secondly, a callback which receive a Core\Route instance, which is just current matched Route, from where being available into callback information about HTTP method, URI, captured parameters, Route callback, etc.

ATTENTION: WHEN one of the Filters returns boolean FALSE, the Routing will generate a “404 Error” for the matched Route even it is a valid matched one.

This is useful to “hide” parts of your website for non-authenticated users or to redirect to a custom “404 Error” page, for example.

Note that Route Filters are defined using “Route::filter()”

How to use this Filter? We use a new style of defining Routes:

Router::post('contact', array( 'filters' => 'csrf', 'uses' => 'App\Controllers\Contact@store' ));

WHERE the Route definition accepts an array as a second parameter and where the keys name is obvious. The key filters’ assign to the value of a ‘|’ separated string of used Route Filters, and the key ‘uses’ assign the associated Callback for the Route.

Running this Route definition, the Routing will be known to apply the Filter with the name ‘csrf’ before the Controller execution, then on CSRF fault, the Filter’s callback will be executed and we go very fast into a redirect.

It’s possible to apply multiple Filters to a Route, using a string containing their name separated by character ‘|’ (pipe).

Usually, we will want to add another two Route Filters and there is a more complex example:

Route::filter('csrf', function($route) { if (($route->method() == 'POST') && ! Csrf::isTokenValid()) { return Redirect::to(''); } }); Route::filter('auth', function($route) { if (Session::get('loggedIn') == false) { return Redirect::to('login'); } }); Route::filter('guest', function($route) { if (Session::get('loggedIn') != false) { return Redirect::to(''); } });

And an example of their usage can be:

Router::any('contact', array( 'filters' => 'guest|csrf', 'uses' => 'App\Controllers\Contact@index' )); Router::any('login', array( 'filters' => 'guest|csrf', 'uses' => 'App\Controllers\Auth@login' )); Router::get('logout', array( 'filters' => 'auth', 'uses' => 'App\Controllers\Auth@logout' ));

WHERE only the only Guest Users can access the Contact and Login page, with CSRF validation, while only the Authenticated Users can access the Logout action.

The alternative usage of Route Filters registering is to use a Class instead of callback, where the called method will receive the matched Route instance as a parameter. For example:

Route::filter('auth', 'App\Helpers\Filters\User@isLoggedIn'); Route::filter('guest', 'App\Helpers\Filters\User@isGuest');

Improvements

An improved Method handling when the Routes are registered and a new Router command called share(), which permit to register multiple Routes all pointing to the same Controller.

For example:

Router::share(array( array('GET', '/'), array('POST', '/home') ), 'App\Controllers\Home@index');

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/143213.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 【Spring Cloud】教你十分钟学会Gateway~

    【Spring Cloud】教你十分钟学会Gateway~SpringCloudGateway是SpringCloud的一个全新项目,该项目是基于Spring5.0,SpringBoot2.0和ProjectReactor(响应式编程)等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的API路由管理方式。………

    2022年10月30日
  • java加密工具类,可设置对应的加解密key

    java加密工具类,可设置对应的加解密key

  • 防止攻击服务器_iis部署网站无法通过ip访问

    防止攻击服务器_iis部署网站无法通过ip访问摘要:介绍了IIS服务器常见的攻击及几种常见防御方式,阐述了IIS服务器的攻击原理,针对IIS服务器的缺陷阐述了IIS的常用防御方式,同时结合实例具体实现方式。关键词:IIS;服务器攻击;服务器防御中图分类号:TP393            文献标识码:A0         引言  随着Internet的不断发展与普及,英特网上出现了越来越多的WEB服务器。人们通过WEB服

  • VLC 外挂字幕乱码

    VLC 外挂字幕乱码title:VLC外挂字幕乱码date:2020-01-2221:11:13tags:技术笔记最近下载了一些电影,使用VLC播放器添加了外挂字幕。问题描述:VLC添加外挂字幕乱码软件环境描述说明下载地址VLC版本3.0.8VLC3.0.8字母格式ASS/SRT字幕库解决方案启动VLC播放器;依次点击左上标题栏…

  • 总结Redis Cluster原理+基本使用+运维注意事项「建议收藏」

    目录一、RedisCluster数据分布理论选择(一)数据分布关注点(二)三种数据分布方案的对比1.节点取余分区方案2.一致性哈希分区方案3.虚拟槽分区方案(RedisCluster采用此方案)二、RedisCluster节点通信概述(一)Gossip消息(二)消息格式分析(三)消息处理流程(四)节点选择(五)通信流程总述三、搭建集群与简单…

  • 数据挖掘——关联规则挖掘

    数据挖掘——关联规则挖掘《数据挖掘》国防科技大学《数据挖掘》青岛大学数据挖掘之关联规则挖掘关联规则挖掘(AssociationRuleMining)最早是由Agrawal等人提出。最初的动机是解决购物篮分析(BasketAnalysis)问题,目的是发现交易数据库(TransactionDatabase)中不同商品之间的联系规则。定义关联规则是描述在一个交易中物品之间同时出现的规律的知识模式,更确切的说,关联规则是通过量化的数字描述物品X的出现对物品Y的出现有多大的影响。关联分析associationana

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号