Laravel 守卫是什么?

我浏览了内置的认证控制器,注意到它们使用了一种叫做“守卫”的东西。到目前为止,每当我自己制作登录/注册表单时,我从来没有碰过这些表单,通常只是做这样的事情:

Auth::attempt()

没有任何类型的警卫。我试着查过这到底是什么,但是我实在找不到任何关于它的信息,谁能告诉我这些守卫的目的是什么?

74898 次浏览

They're the definition of how the system should store and retrieve information about your users.

You can find the configuration in your config/auth.php file. A web guard is the traditional cookie store - so that web guard instructs Laravel to store and retrieve session information the classic way. The API guard, on the other hand, uses tokens. So you would use the API guard if you want to authenticate users and requests using an API token in the header (bearer) or query parameter.

You can also create your own guard if you wish, and there's also this good introductory blog post on the topic by Matt Stauffer.

A guard is a way of supplying the logic that is used to identify authenticated users. Laravel provides different guards like sessions and tokens. The session guard maintains the state of the user in each request by cookies, and on the other hand, the token guard authenticates the user by checking a valid token in every request.

Since I had the same question and the other answers did not provide me the information I was looking for (they explain perfectly what a guard does, but not why you should ever worry about calling its methods), I will provide another answer.

I was also unsure about the difference between methods provided by the auth() helper and methods provided by the guard itself auth()->guard(), as they seemed to do the same.

A quick dd(auth()) reveals that it returns an instance of AuthManager. So we can look up that class in the source code: On the bottom of AuthManager.php there is a __call() magic method which forwards all undefined calls to its own guard() method.

public function __call($method, $parameters)
{
return $this->guard()->{$method}(...$parameters);
}

This clearly shows us that the methods of auth() and auth()->guard() not only seem to do the same, but are exactly the same. So as long as the default guard should be used, an additional ->guard() can be omitted with peace of mind.

Guard role is to authenticate routes

  1. Web guard will authenticate web routes
  2. Api guard will authenticate api routes.
  3. For other user types e.g Admin guard will authenticate admin routes and so on.