search
HomeBackend DevelopmentPHP TutorialLaravel 五 基础(十二)- 认证

Laravel 5 基础(十二)- 认证

Laravel 出厂已经带有了用户认证系统,我们来看一下 routes.php,如果删除了,添加上:

<code>Route::controllers([    'auth' => 'Auth\AuthController',    'password' => 'Auth\PasswordController']);</code>

可以使用 php artisan route:list 查看一下。浏览器中访问 /auth/login,可以看到登陆界面,最好把系统默认的 app.blade.php 中关于 google 的东西注释起来,要不然你会疯掉的。

你可以使用 register、login甚至 forget password。

实际注册一个用户,提交后失败了,实际上没有失败,只是larave自动跳转到了 /home,我们已经删除了这个控制器。你可以使用 tinker 看一下,用户已经建立了。

Auth\AuthController 中实际上使用了 trait,什么是 triat?well,php只支持单继承,在php5.4中添加了trait,一个trait实际上是一组方法的封装,你可以把它包含在另一个类中。像是抽象类,你不能直接实例化他。

Auth\AuthController 中有对 trait 的引用:

<code>use AuthenticatesAndRegistersUsers;</code>

让我们找到他,看一下注册后是怎么跳转的。他隐藏的挺深的,在 vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesAndregistersUsers.php,wow。

<code>	public function redirectPath()	{		if (property_exists($this, &#39;redirectPath&#39;))		{			return $this->redirectPath;		}                //如果用户设置了 redirectTo 属性,则跳转到用户设置的属性,否则到home		return property_exists($this, &#39;redirectTo&#39;) ? $this->redirectTo : &#39;/home&#39;;	}</code>

OK,我们知道了,只要设定 redirectTo 这个属性就可以自定义注册后的跳转了。我们在 Auth\AuthContotroller 中修改:

<code> protected $redirectTo = &#39;articles&#39;;</code>

我们先使用 /auth/logout 确保我们退出,如果出错了不要害怕,我们没有默认的主页,重新访问:auth/register 新建一个用户,这次应该ok了。

再次logout,然后使用 login 登陆一下。

现在我们可以删除 form_partial 中临时设置的隐藏字段了,然后修改控制器:

<code>    public function store(Requests\ArticleRequest $request) {        //你可以这样        //$request = $request->all();        //$request[&#39;user_id&#39;] = Auth::id();        //更简单的方法        $article = Article::create($request->all());        //laravel 自动完成外键关联        Auth::user()->articles()->save($article);        return redirect(&#39;articles&#39;);    }</code>

添加一个文章,然后使用 tinker 查看一下。

中间件

我们当然不希望任何人都能发布文章,至少是登陆用才可以。我们在控制器中添加保护:

<code>    public function create() {        if (Auth::guest()) {            return redirect(&#39;articles&#39;);        }        return view(&#39;articles.create&#39;);    }</code>

上面的代码可以工作,有一个问题,我们需要在每一个需要保护的方法中都进行上面的处理,这样做太傻了,幸好我们有中间件。

中间件可以理解为一个处理管道,中间件在管道中的某一时刻进行处理,这个时刻可以是请求也可以是响应。依据中间件的处理规则,可能将请求重定向,也可能通过请求。

app/http/middleware 中包含了三个中间件,名字就可以看出是干什么,好好查看一下,注意,Closure $next 代表了下一个中间件。

app/http/kernel.php 中对中间件进行登记。$middleware 段声明了对所有http都进行处理的中间件,$routeMiddleware 仅仅对路由进行处理,而且你必须显示的声明要使用这其中的某一个或几个中间件。

假设我们想对整个的 ArticlesController 进行保护,我们直接在构造函数中添加中间件:

<code>    public function __construct() {        $this->middleware(&#39;auth&#39;);    }</code>

现在,任何方法都收到了保护。

但我们可能不想整个控制器都受到保护,如果只是其中的一两个方法呢?我们可以这样处理:

<code>    public function __construct() {        $this->middleware(&#39;auth&#39;, [&#39;only&#39; => &#39;create&#39;]);        //当然可以反过来        //$this->middleware(&#39;auth&#39;, [&#39;except&#39; => &#39;index&#39;]);    }</code>

我们不一定在控制器的构造函数中引入中间件,我们可以直接在路由中声明:

<code>Route::get(&#39;about&#39;, [&#39;middleware&#39; => &#39;auth&#39;, &#39;uses&#39; => &#39;[email&#160;protected]&#39;]);</code>

kernel.php 中提供的系统中间件,比如 'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode' 是可以让我们进入到维护模式,比如系统上线了,但现在需要临时关闭一段时间进行处理,我们可以在命令行进行处理,看一下这个中间件的工作:

<code>php artisan down</code>

访问一下网站,可以看到任何 url 的请求都是马上回来。网站上线:

<code>php artisan up</code>

我们来做一个自己的中间件:

<code> php artisan make:middleware Demo</code>

然后添加代码:

<code>	public function handle($request, Closure $next)	{        //如果请求中含有 foo,我们就回到控制器首页        if ($request->has(&#39;foo&#39;)) {            return redirect(&#39;articles&#39;);        }		return $next($request);	}</code>

如果希望在全部的请求使用中间件,需要在 kernel.php 中的 $middleware 中登记:

<code>	protected $middleware = [		...		&#39;App\Http\Middleware\Demo&#39;,	];</code>

现在我们可以测试一下,假设我们访问 /articles/create?foo=bar ,我们被重定向到了首页。

让我们去除这个显示中间件,我们来创建一个真正有用的中间件。假设我们想保护某个页面,这个页面必须是管理者才能访问的。

<code>php artisan make:middleware RedirectIfNotAManager</code>

我们来添加处理代码:

<code>	public function handle($request, Closure $next)	{        if (!$request->user() || !$request->user()->isATeamManager()) {            return redirect(&#39;articles&#39;);        }		return $next($request);	}</code>

下面修改我们的模型:

<code>    public function isATeamManager() {        return false;    }</code>

简单起见,我们直接返回false。这次我们把中间件放置在 kernel.php 中的$routeMiddleware 中。

<code>	protected $routeMiddleware = [		...		&#39;manager&#39; => &#39;App\Http\Middleware\RedirectIfNotAManager&#39;,	];</code>

我们做一个测试路由测试一下:

<code>Route::get(&#39;foo&#39;, [&#39;middleware&#39; => &#39;manager&#39;, function() {    return &#39;This page may only be viewed by manager&#39;;}]);</code>

guest身份访问或者登录身份访问都会返回主页,但是如果修改 isATeamManager() 返回 true,登录身份访问可以看到返回的信息。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use