Home Backend Development PHP Tutorial Laravel 5框架学习之用户认证_PHP

Laravel 5框架学习之用户认证_PHP

May 29, 2016 am 11:52 AM

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

Route::controllers([
  'auth' => 'Auth\AuthController',
  'password' => 'Auth\PasswordController'
]);
Copy after login

可以使用 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 的引用:

代码如下:


use AuthenticatesAndRegistersUsers;

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

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

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

代码如下:


protected $redirectTo = 'articles';

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

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

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

  public function store(Requests\ArticleRequest $request) {
    //你可以这样
    //$request = $request->all();
    //$request['user_id'] = Auth::id();

    //更简单的方法
    $article = Article::create($request->all());
    //laravel 自动完成外键关联
    Auth::user()->articles()->save($article);

    return redirect('articles');
  }

Copy after login

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

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

  public function create() {
    if (Auth::guest()) {
      return redirect('articles');
    }
    return view('articles.create');
  }
Copy after login

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

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

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

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

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

  public function __construct() {
    $this->middleware('auth');
  }
Copy after login

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

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

  public function __construct() {
    $this->middleware('auth', ['only' => 'create']);
    //当然可以反过来
    //$this->middleware('auth', ['except' => 'index']);
  }
Copy after login

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

代码如下:


Route::get('about', ['middleware' => 'auth', 'uses' => 'PagesController@about']);

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

代码如下:


php artisan down

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

代码如下:


php artisan up

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

代码如下:


php artisan make:middleware Demo

然后添加代码:

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

 return $next($request);
 }

Copy after login

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

 protected $middleware = [
 ...
 'App\Http\Middleware\Demo',

 ];

Copy after login

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

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

代码如下:


php artisan make:middleware RedirectIfNotAManager

我们来添加处理代码:

 public function handle($request, Closure $next)
 {
    if (!$request->user() || !$request->user()->isATeamManager()) {
      return redirect('articles');
    }

 return $next($request);
 }

Copy after login

下面修改我们的模型:

  public function isATeamManager() {
    return false;
  }
Copy after login

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

 protected $routeMiddleware = [
 ...
 'manager' => 'App\Http\Middleware\RedirectIfNotAManager',
 ];
Copy after login

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

Route::get('foo', ['middleware' => 'manager', function() {
  return 'This page may only be viewed by manager';
}]);
Copy after login

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

以上就是本文所述的全部内容,希望对大家熟悉Laravel5框架能够有所帮助。

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles