Перейти к содержимому

Как получить данные авторизированного пользователя laravel

  • автор:

Authentication

Many web applications provide a way for their users to authenticate with the application and "login". Implementing this feature in web applications can be a complex and potentially risky endeavor. For this reason, Laravel strives to give you the tools you need to implement authentication quickly, securely, and easily.

At its core, Laravel’s authentication facilities are made up of "guards" and "providers". Guards define how users are authenticated for each request. For example, Laravel ships with a session guard which maintains state using session storage and cookies.

Providers define how users are retrieved from your persistent storage. Laravel ships with support for retrieving users using Eloquent and the database query builder. However, you are free to define additional providers as needed for your application.

Your application’s authentication configuration file is located at config/auth.php . This file contains several well-documented options for tweaking the behavior of Laravel’s authentication services.

Note
Guards and providers should not be confused with "roles" and "permissions". To learn more about authorizing user actions via permissions, please refer to the authorization documentation.

Starter Kits

Want to get started fast? Install a Laravel application starter kit in a fresh Laravel application. After migrating your database, navigate your browser to /register or any other URL that is assigned to your application. The starter kits will take care of scaffolding your entire authentication system!

Even if you choose not to use a starter kit in your final Laravel application, installing the Laravel Breeze starter kit can be a wonderful opportunity to learn how to implement all of Laravel’s authentication functionality in an actual Laravel project. Since Laravel Breeze creates authentication controllers, routes, and views for you, you can examine the code within these files to learn how Laravel’s authentication features may be implemented.

Database Considerations

By default, Laravel includes an App\Models\User Eloquent model in your app/Models directory. This model may be used with the default Eloquent authentication driver. If your application is not using Eloquent, you may use the database authentication provider which uses the Laravel query builder.

When building the database schema for the App\Models\User model, make sure the password column is at least 60 characters in length. Of course, the users table migration that is included in new Laravel applications already creates a column that exceeds this length.

Also, you should verify that your users (or equivalent) table contains a nullable, string remember_token column of 100 characters. This column will be used to store a token for users that select the "remember me" option when logging into your application. Again, the default users table migration that is included in new Laravel applications already contains this column.

Ecosystem Overview

Laravel offers several packages related to authentication. Before continuing, we’ll review the general authentication ecosystem in Laravel and discuss each package’s intended purpose.

First, consider how authentication works. When using a web browser, a user will provide their username and password via a login form. If these credentials are correct, the application will store information about the authenticated user in the user’s session. A cookie issued to the browser contains the session ID so that subsequent requests to the application can associate the user with the correct session. After the session cookie is received, the application will retrieve the session data based on the session ID, note that the authentication information has been stored in the session, and will consider the user as "authenticated".

When a remote service needs to authenticate to access an API, cookies are not typically used for authentication because there is no web browser. Instead, the remote service sends an API token to the API on each request. The application may validate the incoming token against a table of valid API tokens and "authenticate" the request as being performed by the user associated with that API token.

Laravel’s Built-in Browser Authentication Services

Laravel includes built-in authentication and session services which are typically accessed via the Auth and Session facades. These features provide cookie-based authentication for requests that are initiated from web browsers. They provide methods that allow you to verify a user’s credentials and authenticate the user. In addition, these services will automatically store the proper authentication data in the user’s session and issue the user’s session cookie. A discussion of how to use these services is contained within this documentation.

Application Starter Kits

As discussed in this documentation, you can interact with these authentication services manually to build your application’s own authentication layer. However, to help you get started more quickly, we have released free packages that provide robust, modern scaffolding of the entire authentication layer. These packages are Laravel Breeze, Laravel Jetstream, and Laravel Fortify.

Laravel Breeze is a simple, minimal implementation of all of Laravel’s authentication features, including login, registration, password reset, email verification, and password confirmation. Laravel Breeze’s view layer is comprised of simple Blade templates styled with Tailwind CSS. To get started, check out the documentation on Laravel’s application starter kits.

Laravel Fortify is a headless authentication backend for Laravel that implements many of the features found in this documentation, including cookie-based authentication as well as other features such as two-factor authentication and email verification. Fortify provides the authentication backend for Laravel Jetstream or may be used independently in combination with Laravel Sanctum to provide authentication for an SPA that needs to authenticate with Laravel.

Laravel Jetstream is a robust application starter kit that consumes and exposes Laravel Fortify’s authentication services with a beautiful, modern UI powered by Tailwind CSS, Livewire, and / or Inertia. Laravel Jetstream includes optional support for two-factor authentication, team support, browser session management, profile management, and built-in integration with Laravel Sanctum to offer API token authentication. Laravel’s API authentication offerings are discussed below.

Laravel’s API Authentication Services

Laravel provides two optional packages to assist you in managing API tokens and authenticating requests made with API tokens: Passport and Sanctum. Please note that these libraries and Laravel’s built-in cookie based authentication libraries are not mutually exclusive. These libraries primarily focus on API token authentication while the built-in authentication services focus on cookie based browser authentication. Many applications will use both Laravel’s built-in cookie based authentication services and one of Laravel’s API authentication packages.

Passport

Passport is an OAuth2 authentication provider, offering a variety of OAuth2 "grant types" which allow you to issue various types of tokens. In general, this is a robust and complex package for API authentication. However, most applications do not require the complex features offered by the OAuth2 spec, which can be confusing for both users and developers. In addition, developers have been historically confused about how to authenticate SPA applications or mobile applications using OAuth2 authentication providers like Passport.

Sanctum

In response to the complexity of OAuth2 and developer confusion, we set out to build a simpler, more streamlined authentication package that could handle both first-party web requests from a web browser and API requests via tokens. This goal was realized with the release of Laravel Sanctum, which should be considered the preferred and recommended authentication package for applications that will be offering a first-party web UI in addition to an API, or will be powered by a single-page application (SPA) that exists separately from the backend Laravel application, or applications that offer a mobile client.

Laravel Sanctum is a hybrid web / API authentication package that can manage your application’s entire authentication process. This is possible because when Sanctum based applications receive a request, Sanctum will first determine if the request includes a session cookie that references an authenticated session. Sanctum accomplishes this by calling Laravel’s built-in authentication services which we discussed earlier. If the request is not being authenticated via a session cookie, Sanctum will inspect the request for an API token. If an API token is present, Sanctum will authenticate the request using that token. To learn more about this process, please consult Sanctum’s "how it works" documentation.

Laravel Sanctum is the API package we have chosen to include with the Laravel Jetstream application starter kit because we believe it is the best fit for the majority of web application’s authentication needs.

Summary & Choosing Your Stack

In summary, if your application will be accessed using a browser and you are building a monolithic Laravel application, your application will use Laravel’s built-in authentication services.

Next, if your application offers an API that will be consumed by third parties, you will choose between Passport or Sanctum to provide API token authentication for your application. In general, Sanctum should be preferred when possible since it is a simple, complete solution for API authentication, SPA authentication, and mobile authentication, including support for "scopes" or "abilities".

If you are building a single-page application (SPA) that will be powered by a Laravel backend, you should use Laravel Sanctum. When using Sanctum, you will either need to manually implement your own backend authentication routes or utilize Laravel Fortify as a headless authentication backend service that provides routes and controllers for features such as registration, password reset, email verification, and more.

Passport may be chosen when your application absolutely needs all of the features provided by the OAuth2 specification.

And, if you would like to get started quickly, we are pleased to recommend Laravel Breeze as a quick way to start a new Laravel application that already uses our preferred authentication stack of Laravel’s built-in authentication services and Laravel Sanctum.

Authentication Quickstart

Warning
This portion of the documentation discusses authenticating users via the Laravel application starter kits, which includes UI scaffolding to help you get started quickly. If you would like to integrate with Laravel’s authentication systems directly, check out the documentation on manually authenticating users.

Install A Starter Kit

First, you should install a Laravel application starter kit. Our current starter kits, Laravel Breeze and Laravel Jetstream, offer beautifully designed starting points for incorporating authentication into your fresh Laravel application.

Laravel Breeze is a minimal, simple implementation of all of Laravel’s authentication features, including login, registration, password reset, email verification, and password confirmation. Laravel Breeze’s view layer is made up of simple Blade templates styled with Tailwind CSS. Breeze also offers an Inertia based scaffolding option using Vue or React.

Laravel Jetstream is a more robust application starter kit that includes support for scaffolding your application with Livewire or Inertia and Vue. In addition, Jetstream features optional support for two-factor authentication, teams, profile management, browser session management, API support via Laravel Sanctum, account deletion, and more.

Retrieving The Authenticated User

After installing an authentication starter kit and allowing users to register and authenticate with your application, you will often need to interact with the currently authenticated user. While handling an incoming request, you may access the authenticated user via the Auth facade’s user method:

Alternatively, once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request instance. Remember, type-hinted classes will automatically be injected into your controller methods. By type-hinting the Illuminate\Http\Request object, you may gain convenient access to the authenticated user from any controller method in your application via the request’s user method:

Determining If The Current User Is Authenticated

To determine if the user making the incoming HTTP request is authenticated, you may use the check method on the Auth facade. This method will return true if the user is authenticated:

Note
Even though it is possible to determine if a user is authenticated using the check method, you will typically use a middleware to verify that the user is authenticated before allowing the user access to certain routes / controllers. To learn more about this, check out the documentation on protecting routes.

Protecting Routes

Route middleware can be used to only allow authenticated users to access a given route. Laravel ships with an auth middleware, which references the Illuminate\Auth\Middleware\Authenticate class. Since this middleware is already registered in your application’s HTTP kernel, all you need to do is attach the middleware to a route definition:

Redirecting Unauthenticated Users

When the auth middleware detects an unauthenticated user, it will redirect the user to the login named route. You may modify this behavior by updating the redirectTo function in your application’s app/Http/Middleware/Authenticate.php file:

Specifying A Guard

When attaching the auth middleware to a route, you may also specify which "guard" should be used to authenticate the user. The guard specified should correspond to one of the keys in the guards array of your auth.php configuration file:

Login Throttling

If you are using the Laravel Breeze or Laravel Jetstream starter kits, rate limiting will automatically be applied to login attempts. By default, the user will not be able to login for one minute if they fail to provide the correct credentials after several attempts. The throttling is unique to the user’s username / email address and their IP address.

Note
If you would like to rate limit other routes in your application, check out the rate limiting documentation.

Manually Authenticating Users

You are not required to use the authentication scaffolding included with Laravel’s application starter kits. If you choose not to use this scaffolding, you will need to manage user authentication using the Laravel authentication classes directly. Don’t worry, it’s a cinch!

We will access Laravel’s authentication services via the Auth facade, so we’ll need to make sure to import the Auth facade at the top of the class. Next, let’s check out the attempt method. The attempt method is normally used to handle authentication attempts from your application’s "login" form. If authentication is successful, you should regenerate the user’s session to prevent session fixation:

The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column. If the user is found, the hashed password stored in the database will be compared with the password value passed to the method via the array. You should not hash the incoming request’s password value, since the framework will automatically hash the value before comparing it to the hashed password in the database. An authenticated session will be started for the user if the two hashed passwords match.

Remember, Laravel’s authentication services will retrieve users from your database based on your authentication guard’s "provider" configuration. In the default config/auth.php configuration file, the Eloquent user provider is specified and it is instructed to use the App\Models\User model when retrieving users. You may change these values within your configuration file based on the needs of your application.

The attempt method will return true if authentication was successful. Otherwise, false will be returned.

The intended method provided by Laravel’s redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.

Specifying Additional Conditions

If you wish, you may also add extra query conditions to the authentication query in addition to the user’s email and password. To accomplish this, we may simply add the query conditions to the array passed to the attempt method. For example, we may verify that the user is marked as "active":

For complex query conditions, you may provide a closure in your array of credentials. This closure will be invoked with the query instance, allowing you to customize the query based on your application’s needs:

Warning
In these examples, email is not a required option, it is merely used as an example. You should use whatever column name corresponds to a "username" in your database table.

The attemptWhen method, which receives a closure as its second argument, may be used to perform more extensive inspection of the potential user before actually authenticating the user. The closure receives the potential user and should return true or false to indicate if the user may be authenticated:

Accessing Specific Guard Instances

Via the Auth facade’s guard method, you may specify which guard instance you would like to utilize when authenticating the user. This allows you to manage authentication for separate parts of your application using entirely separate authenticatable models or user tables.

The guard name passed to the guard method should correspond to one of the guards configured in your auth.php configuration file:

Remembering Users

Many web applications provide a "remember me" checkbox on their login form. If you would like to provide "remember me" functionality in your application, you may pass a boolean value as the second argument to the attempt method.

When this value is true , Laravel will keep the user authenticated indefinitely or until they manually logout. Your users table must include the string remember_token column, which will be used to store the "remember me" token. The users table migration included with new Laravel applications already includes this column:

If your application offers "remember me" functionality, you may use the viaRemember method to determine if the currently authenticated user was authenticated using the "remember me" cookie:

Other Authentication Methods

Authenticate A User Instance

If you need to set an existing user instance as the currently authenticated user, you may pass the user instance to the Auth facade’s login method. The given user instance must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract. The App\Models\User model included with Laravel already implements this interface. This method of authentication is useful when you already have a valid user instance, such as directly after a user registers with your application:

You may pass a boolean value as the second argument to the login method. This value indicates if "remember me" functionality is desired for the authenticated session. Remember, this means that the session will be authenticated indefinitely or until the user manually logs out of the application:

If needed, you may specify an authentication guard before calling the login method:

Authenticate A User By ID

To authenticate a user using their database record’s primary key, you may use the loginUsingId method. This method accepts the primary key of the user you wish to authenticate:

You may pass a boolean value as the second argument to the loginUsingId method. This value indicates if "remember me" functionality is desired for the authenticated session. Remember, this means that the session will be authenticated indefinitely or until the user manually logs out of the application:

Authenticate A User Once

You may use the once method to authenticate a user with the application for a single request. No sessions or cookies will be utilized when calling this method:

HTTP Basic Authentication

HTTP Basic Authentication provides a quick way to authenticate users of your application without setting up a dedicated "login" page. To get started, attach the auth.basic middleware to a route. The auth.basic middleware is included with the Laravel framework, so you do not need to define it:

Once the middleware has been attached to the route, you will automatically be prompted for credentials when accessing the route in your browser. By default, the auth.basic middleware will assume the email column on your users database table is the user’s "username".

A Note On FastCGI

If you are using PHP FastCGI and Apache to serve your Laravel application, HTTP Basic authentication may not work correctly. To correct these problems, the following lines may be added to your application’s .htaccess file:

Stateless HTTP Basic Authentication

You may also use HTTP Basic Authentication without setting a user identifier cookie in the session. This is primarily helpful if you choose to use HTTP Authentication to authenticate requests to your application’s API. To accomplish this, define a middleware that calls the onceBasic method. If no response is returned by the onceBasic method, the request may be passed further into the application:

Next, attach the middleware to a route:

Logging Out

To manually log users out of your application, you may use the logout method provided by the Auth facade. This will remove the authentication information from the user’s session so that subsequent requests are not authenticated.

In addition to calling the logout method, it is recommended that you invalidate the user’s session and regenerate their CSRF token. After logging the user out, you would typically redirect the user to the root of your application:

Invalidating Sessions On Other Devices

Laravel also provides a mechanism for invalidating and "logging out" a user’s sessions that are active on other devices without invalidating the session on their current device. This feature is typically utilized when a user is changing or updating their password and you would like to invalidate sessions on other devices while keeping the current device authenticated.

Before getting started, you should make sure that the Illuminate\Session\Middleware\AuthenticateSession middleware is included on the routes that should receive session authentication. Typically, you should place this middleware on a route group definition so that it can be applied to the majority of your application’s routes. By default, the AuthenticateSession middleware may be attached to a route using the auth.session route middleware alias as defined in your application’s HTTP kernel:

Then, you may use the logoutOtherDevices method provided by the Auth facade. This method requires the user to confirm their current password, which your application should accept through an input form:

When the logoutOtherDevices method is invoked, the user’s other sessions will be invalidated entirely, meaning they will be "logged out" of all guards they were previously authenticated by.

Password Confirmation

While building your application, you may occasionally have actions that should require the user to confirm their password before the action is performed or before the user is redirected to a sensitive area of the application. Laravel includes built-in middleware to make this process a breeze. Implementing this feature will require you to define two routes: one route to display a view asking the user to confirm their password and another route to confirm that the password is valid and redirect the user to their intended destination.

Note
The following documentation discusses how to integrate with Laravel’s password confirmation features directly; however, if you would like to get started more quickly, the Laravel application starter kits include support for this feature!

Configuration

After confirming their password, a user will not be asked to confirm their password again for three hours. However, you may configure the length of time before the user is re-prompted for their password by changing the value of the password_timeout configuration value within your application’s config/auth.php configuration file.

Routing

The Password Confirmation Form

First, we will define a route to display a view that requests the user to confirm their password:

As you might expect, the view that is returned by this route should have a form containing a password field. In addition, feel free to include text within the view that explains that the user is entering a protected area of the application and must confirm their password.

Confirming The Password

Next, we will define a route that will handle the form request from the "confirm password" view. This route will be responsible for validating the password and redirecting the user to their intended destination:

Before moving on, let’s examine this route in more detail. First, the request’s password field is determined to actually match the authenticated user’s password. If the password is valid, we need to inform Laravel’s session that the user has confirmed their password. The passwordConfirmed method will set a timestamp in the user’s session that Laravel can use to determine when the user last confirmed their password. Finally, we can redirect the user to their intended destination.

Protecting Routes

You should ensure that any route that performs an action which requires recent password confirmation is assigned the password.confirm middleware. This middleware is included with the default installation of Laravel and will automatically store the user’s intended destination in the session so that the user may be redirected to that location after confirming their password. After storing the user’s intended destination in the session, the middleware will redirect the user to the password.confirm named route:

Adding Custom Guards

You may define your own authentication guards using the extend method on the Auth facade. You should place your call to the extend method within a service provider. Since Laravel already ships with an AuthServiceProvider , we can place the code in that provider:

As you can see in the example above, the callback passed to the extend method should return an implementation of Illuminate\Contracts\Auth\Guard . This interface contains a few methods you will need to implement to define a custom guard. Once your custom guard has been defined, you may reference the guard in the guards configuration of your auth.php configuration file:

Closure Request Guards

The simplest way to implement a custom, HTTP request based authentication system is by using the Auth::viaRequest method. This method allows you to quickly define your authentication process using a single closure.

To get started, call the Auth::viaRequest method within the boot method of your AuthServiceProvider . The viaRequest method accepts an authentication driver name as its first argument. This name can be any string that describes your custom guard. The second argument passed to the method should be a closure that receives the incoming HTTP request and returns a user instance or, if authentication fails, null :

Once your custom authentication driver has been defined, you may configure it as a driver within the guards configuration of your auth.php configuration file:

Finally, you may reference the guard when assigning the authentication middleware to a route:

Adding Custom User Providers

If you are not using a traditional relational database to store your users, you will need to extend Laravel with your own authentication user provider. We will use the provider method on the Auth facade to define a custom user provider. The user provider resolver should return an implementation of Illuminate\Contracts\Auth\UserProvider :

After you have registered the provider using the provider method, you may switch to the new user provider in your auth.php configuration file. First, define a provider that uses your new driver:

Finally, you may reference this provider in your guards configuration:

The User Provider Contract

Illuminate\Contracts\Auth\UserProvider implementations are responsible for fetching an Illuminate\Contracts\Auth\Authenticatable implementation out of a persistent storage system, such as MySQL, MongoDB, etc. These two interfaces allow the Laravel authentication mechanisms to continue functioning regardless of how the user data is stored or what type of class is used to represent the authenticated user:

Let’s take a look at the Illuminate\Contracts\Auth\UserProvider contract:

The retrieveById function typically receives a key representing the user, such as an auto-incrementing ID from a MySQL database. The Authenticatable implementation matching the ID should be retrieved and returned by the method.

The retrieveByToken function retrieves a user by their unique $identifier and "remember me" $token , typically stored in a database column like remember_token . As with the previous method, the Authenticatable implementation with a matching token value should be returned by this method.

The updateRememberToken method updates the $user instance’s remember_token with the new $token . A fresh token is assigned to users on a successful "remember me" authentication attempt or when the user is logging out.

The retrieveByCredentials method receives the array of credentials passed to the Auth::attempt method when attempting to authenticate with an application. The method should then "query" the underlying persistent storage for the user matching those credentials. Typically, this method will run a query with a "where" condition that searches for a user record with a "username" matching the value of $credentials[‘username’] . The method should return an implementation of Authenticatable . This method should not attempt to do any password validation or authentication.

The validateCredentials method should compare the given $user with the $credentials to authenticate the user. For example, this method will typically use the Hash::check method to compare the value of $user->getAuthPassword() to the value of $credentials[‘password’] . This method should return true or false indicating whether the password is valid.

The Authenticatable Contract

Now that we have explored each of the methods on the UserProvider , let’s take a look at the Authenticatable contract. Remember, user providers should return implementations of this interface from the retrieveById , retrieveByToken , and retrieveByCredentials methods:

This interface is simple. The getAuthIdentifierName method should return the name of the "primary key" field of the user and the getAuthIdentifier method should return the "primary key" of the user. When using a MySQL back-end, this would likely be the auto-incrementing primary key assigned to the user record. The getAuthPassword method should return the user’s hashed password.

This interface allows the authentication system to work with any "user" class, regardless of what ORM or storage abstraction layer you are using. By default, Laravel includes a App\Models\User class in the app/Models directory which implements this interface.

Events

Laravel dispatches a variety of events during the authentication process. You may attach listeners to these events in your EventServiceProvider :

Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in most web projects.

  • Our Team
  • Release Notes
  • Getting Started
  • Routing
  • Blade Templates
  • Authentication
  • Authorization
  • Artisan Console
  • Database
  • Eloquent ORM
  • Testing
  • Laravel Bootcamp
  • Laracasts
  • Laravel News
  • Laracon
  • Laracon AU
  • Laracon EU
  • Laracon India
  • Jobs
  • Forums
  • Shop
  • Trademark
  • WebReinvent
  • Vehikl
  • Tighten
  • 64 Robots
  • Active Logic
  • Byte 5
  • Curotec
  • Cyber-Duck
  • DevSquad
  • Jump24
  • Kirschbaum
  • Cashier
  • Dusk
  • Echo
  • Envoyer
  • Forge
  • Herd
  • Horizon
  • Nova
  • Octane
  • Pennant
  • Sail
  • Sanctum
  • Scout
  • Spark
  • Telescope
  • Vapor

Laravel is a Trademark of Taylor Otwell. Copyright © 2011-2023 Laravel LLC.

Аутентификация

Аутентификация — это процесс регистрации и логина пользователей. Не путайте с авторизацией — проверкой прав уже залогиненного пользователя.

Хотите быстро начать работу? Установите composer-пакет laravel/ui (1.0) и запустите php artisan ui vue —auth в свежем приложении Laravel. Запустите миграцию базы данных и зайдите на http://your-app.test/register . У вас появилась готовая система аутентификации, которую вы можете менять под себя как захотите!

В Laravel сделать аутентификацию очень просто. Фактически, почти всё сконфигурировано для вас уже изначально. Конфигурационный файл аутентификации расположен в config/auth.php , он содержит несколько хорошо описанных опций для тонкой настройки поведения служб аутентификации.

По сути средства аутентификации Laravel состоят из "гвардов" и "провайдеров". Гварды определяют то, как именно аутентифицируются пользователи, для каждого запроса. Например, Laravel поставляется с гвардом session , который поддерживает состояние аутентифицированности с помощью хранилища сессий и кук.

Провайдеры определяют то, как именно пользователи извлекаются из вашей базы данных. Laravel поставляется с поддержкой извлечения пользователей с помощью Eloquent и конструктора запросов БД. Но при необходимости вы можете определить дополнительные провайдеры для своего приложения.

Не переживайте, если сейчас это звучит слишком запутанно! Для большинства приложений никогда не потребуется изменять стандартные настройки аутентификации.

Требования для базы данных

По умолчанию в Laravel есть модель Eloquent App\User в директории app . Эта модель может использоваться с базовым драйвером аутентификации Eloquent. Если ваше приложение не использует Eloquent, вы можете использовать драйвер аутентификации database , который использует конструктор запросов Laravel.

При создании схемы базы данных для модели App\User создайте столбец для паролей с длиной не менее 60 символов. Хорошим выбором будет длина 255 символов.

Кроме того, перед началом работы удостоверьтесь, что ваша таблица users (или эквивалентная) содержит строковый столбец remember_token на 100 символов. Этот столбец будет использоваться для хранения ключей сессий «запомнить меня», обрабатываемых вашим приложением.

Краткое руководство по аутентификации

Laravel поставляется с несколькими контроллерами аутентификации, расположенными в пространстве имён App\Http\Controllers\Auth . RegisterController обрабатывает регистрацию нового пользователя, LoginController — его аутентификацию, ForgotPasswordController обрабатывает отправку по электронной почте ссылок на сброс пароля, а ResetPasswordController содержит логику для сброса паролей. Каждый из этих контроллеров использует типажи для подключения необходимых методов. Для многих приложений вам вообще не придётся изменять эти контроллеры.

Роутинг

Laravel обеспечивает быстрый способ создания заготовок всех необходимых для аутентификации роутов и шаблонов при помощи пакета laravel/ui :

Эту команду надо использовать на свежем приложении, она установит шаблоны для регистрации и логина, а также роуты, требуемые для системы аутентификации. Также будет сгенерирован HomeController , на коорый будет сделан редирект залогиненного пользователя. Но вы можете изменить или даже удалить это контроллер, если это необходимо для вашего приложения.

Если вы хотите запретить регистрацию, удалите контроллер RegisterController , который также делает эта команда, и измените роуты аутентификации: Auth::routes([‘register’ => false]); .

Создание системы аутентификации вместе с созданием приложения

На этапе создания приложения вы можете указать флаг —auth и инсталлятор сразу добавит систему аутентификации:

Шаблоны

Как было упомянуто в предыдущем разделе, команда php artisan ui vue —auth из пакета laravel/ui создаст все необходимые вам шаблоны для аутентификации и поместит их в директорию resources/views/auth .

Команда ui также создаст директорию resources/views/layouts , содержащую основной макет для вашего приложения. Все эти макеты используют CSS-фреймворк Bootstrap, но вы можете изменять их как угодно.

Аутентификация

Теперь, когда у вас есть роуты и шаблоны для имеющихся контроллеров аутентификации, вы готовы регистрировать и аутентифицировать новых пользователей своего приложения! Вы можете просто перейти по этим роутам в браузере. Контроллеры аутентификации уже содержат логику (благодаря их типажам) для аутентификации существующих пользователей и сохранения новых пользователей в базе данных.

Изменение пути

Когда пользователь успешно аутентифицируется, он будет перенаправлен на URI /home . Вы можете изменить место для перенаправления после входа, задав константу HOME в сервис-провайдере RouteServiceProvider :

Если вам нужна более гибкая настройка ответа, возвращаемого при аутентификации пользователя, Laravel предоставляет пустой метод authenticated(Request $request, $user) , который, при желании, может быть переопределен:

Настройка имени пользователя

По умолчанию для аутентификации Laravel использует поле email . Если вы хотите это изменить, то можете определить метод username в своем LoginController :

Настройка гварда

Вы также можете изменить "гварда", который используется для аутентификации и регистрации пользователей. Для начала задайте метод guard в LoginController , RegisterController и ResetPasswordController . Метод должен возвращать экземпляр гварда:

Настройка валидации / хранения

Чтобы изменить требуемые поля для формы регистрации нового пользователя, или для изменения способа добавления новых записей в вашу базу данных, вы можете изменить класс RegisterController . Этот класс отвечает за проверку ввода и создание новых пользователей в вашем приложении.

Метод validator класса RegisterController содержит правила проверки ввода данных для новых пользователей приложения.

Метод create класса RegisterController отвечает за создание новых записей App\User в вашей базе данных с помощью Eloquent ORM. Вы можете изменить каждый из этих методов, как пожелаете.

Получение аутентифицированного пользователя

Вы можете обращаться к аутентифицированному пользователю через фасад Auth :

Или, когда пользователь аутентифицирован, вы можете обращаться к нему через экземпляр Illuminate\Http\Request . Не забывайте, что указание типов классов приводит к их автоматическому внедрению в методы вашего контроллера:

Определение, аутентифицирован ли пользователь

Чтобы определить, что пользователь уже вошёл в ваше приложение, вы можете использовать метод check фасада Auth , который вернёт true , если пользователь аутентифицирован:

Хотя и возможно определить аутентифицирован ли пользователь, используя метод check , обычно вы будете использовать посредников для проверки был ли пользователь аутентифицирован ранее, позволяя этому пользователю получать доступ к определенным роутам / контроллерам. Для получения дополнительной информации смотрите документацию о защите роутов.

Защита роутов

Чтобы давать доступ к определённому роуту только аутентифицированным пользователям можно использовать специальный посредник (middleware). Laravel поставляется с посредником auth , который определён в Illuminate\Auth\Middleware\Authenticate . Так как этот посредник уже зарегистрирован в фреймворке и всё, что вам надо сделать — это присоединить его к определению роута:

Вы также можете вызвать метод middleware из конструктора контроллера, вместо присоединения его напрямую к определению роута:

Обработка неаутентифицированных пользователей

Когда посредник auth определяет, что пользователь неаутентифицирован, он перенаправляет его на роут с именем login . Вы можете изменить это поведение в методе redirectTo класса app/Http/Middleware/Authenticate.php :

Указание гварда

Во время прикрепления посредника auth к роуту, вы можете также указать, какой гвард должен быть использован для выполнения аутентификации. Указанный гвард должен соответствовать одному из ключей в массиве guards вашего конфига auth.php :

Защита повторным вводом пароля

Особо важные места сайта (изменение критичных настроек — например, платёжной информации) можно защитить путём повторного запроса пароля у пользователя.

Для этого защитите роут или группу роутов посредником password.confirm . При заходе на этот урл будет произведён редирект на промежуточную страницу с формой ввода пароля.

После успешного ввода пароля произойдёт редирект на защищаемый роут. При повтором входе на этот роут пароль не будет спрашиваться в течении трёх часов. Вы можете изменить это время путём редактирования опции auth.password_timeout в конфиге.

Троттлинг аутентификации (ограничение числа неудачных попыток входа)

Если вы используете встроенный в Laravel класс LoginController , трейт Illuminate\Foundation\Auth\ThrottlesLogins уже будет включён в ваш контроллер. По умолчанию пользователь не сможет войти в приложение в течение одной минуты, если он несколько раз указал неправильные данные для входа. Ограничение происходит отдельно для имени пользователя/адреса e-mail и его IP-адреса.

Аутентификация пользователей вручную

Вы можете написать свои контроллеры аутентификации пользователей, не пользоваться теми, что генерирует фреймворк, если по какой-то причине они вас не устраивают. Для этого вам нужно использовать в своих контроллерах классы аутентификации Laravel. Не волнуйтесь, это просто.

Мы будем работать со службами аутентификации Laravel через фасад Auth , поэтому нам надо не забыть импортировать фасад Auth в начале класса. Далее давайте посмотрим на метод attempt :

Метод attempt принимает массив пар ключ/значение в качестве первого аргумента. Значения массива будут использованы для поиска пользователя в таблице базы данных. Так, в приведённом выше примере пользователь будет получен по значению столбца email . Если пользователь будет найден, хешированный пароль, сохранённый в базе данных, будет сравниваться с хешированным значением password , переданным в метод через массив. Вы не должны хешировать пароль, указанный в качестве значения password , поскольку фреймворк автоматически хеширует значение, прежде чем сравнивать его с хешированным паролем в базе данных. Если два хешированных пароля совпадут, то для пользователя будет запущена новая аутентифицированная сессия.

Метод attempt вернет true , если аутентификация прошла успешно. В противном случае будет возвращён false .

Метод intended "редиректора" перенаправит пользователя к тому URL, к которому он обращался до того, как был перехвачен фильтром аутентификации. В этот метод можно передать запасной URI, на случай недоступности требуемого пути.

Указание дополнительных условий

При необходимости вы можете добавить дополнительные условия к запросу аутентификации, помимо адреса e-mail и пароля. Например, можно проверить отметку "активности" пользователя:

В этих примерах email не является обязательным вариантом, он приведён только для примера. Вы можете использовать какой угодно столбец, соответствующий "username" в вашей базе данных.

Обращение к конкретным экземплярам гварда

С помощью метода guard фасада Auth вы можете указать, какой экземпляр гварда необходимо использовать. Это позволяет управлять аутентификацией для отдельных частей вашего приложения, используя полностью отдельные модели для аутентификации или таблицы пользователей.

Передаваемое в метод guard имя гварда должно соответствовать одному из защитников, настроенных в конфиге auth.php :

Завершение сессии

Для завершения сессии пользователя можно использовать метод logout фасада Auth . Он очистит информацию об аутентификации в сессии пользователя:

Запоминание пользователей

Если вы хотите обеспечить функциональность "запомнить меня" в вашем приложении, вы можете передать логическое значение как второй параметр методу attempt , который сохранит пользователя аутентифицированным на неопределённое время, или пока он вручную не выйдет из системы. Ваша таблица users должна содержать строковый столбец remember_token , который будет использоваться для хранения токенов "запомнить меня".

Если вы используете встроенный в Laravel LoginController , логика "запоминания" пользователей уже реализована трейтами, используемыми контроллером.

Если вы "запоминаете" пользователей, то можете использовать метод viaRemember , чтобы определить, аутентифицировался ли пользователь, используя cookie "запомнить меня":

Другие методы аутентификации

Аутентификация экземпляра пользователя

Если вам необходимо "залогинить" в приложение существующий экземпляр пользователя, вызовите метод login с экземпляром пользователя. Данный объект должен быть реализацией контракта Illuminate\Contracts\Auth\Authenticatable . Конечно, встроенная в Laravel модель App\User реализует этот интерфейс:

Конечно, вы можете указать, какой экземпляр гварда надо использовать:

Аутентификация пользователя по ID

Для входа пользователя в приложение по его ID, используйте метод loginUsingId . Этот метод просто принимает первичный ключ пользователя, которого необходимо аутентифицировать:

Однократная аутентификация пользователя

Вы также можете использовать метод once для пользовательского входа в систему для одного запроса. Сеансы и cookies не будут использоваться, что может быть полезно при создании API без сохранения состояний:

HTTP-аутентификация

HTTP-аутентификация — простой и быстрый способ аутентификации пользователей вашего приложения без создания дополнительной страницы входа. Для начала прикрепите посредника auth.basic к своему роуту. Посредник auth.basic встроен в Laravel, поэтому вам не надо определять его:

Когда посредник прикреплён к роуту, вы автоматически получите запрос данных для входа при обращении к роуту через браузер. По умолчанию посредник auth.basic будет использовать столбец email из записи пользователя в качестве "username".

Замечание по FastCGI

Если вы используете PHP FastCGI, то простая HTTP-аутентификация изначально может работать неправильно. Надо добавить следующие строки к вашему файлу .htaccess :

HTTP-аутентификация без сохранения состояния

Вы также можете использовать HTTP-аутентификацию, не задавая пользовательскую cookie для сессии, что особенно полезно для API-аутентификации. Чтобы это сделать, определите посредника, который вызывает метод onceBasic . Если этот метод ничего не возвращает, запрос может быть передан дальше в приложение:

Завершение сессии

Чтобы разлогинить пользователя используйте метод logout фасада Auth . Он очистит информацию об аутентификации в сессии пользователя:

Инвалидация сессий на других устройствах

В Laravel есть механизм для завершении сессии на других устройствах (браузерах), оставляя сессию на данном устройстве активной. Например, это требуется когда пользователь изменяет свой пароль.

Чтобы этот функционал работал, в app/Http/Kernel.php в секции web должен быть добавлен посредник Illuminate\Session\Middleware\AuthenticateSession

Теперь вы можете использовать метод logoutOtherDevices фасада Auth . В качестве аргумента он принимает текущий пароль пользователя.

При вызове метода logoutOtherDevices все сессии пользователя кроме текущей будут инвалидированы, что означает, что пользователь будет "разлогинен" во всех гвардах, в которых он был ранее аутентифицирован.

При использовании посредника AuthenticateSession вместе с нестандартным именем маршрута login , вы должны переопределить метод unauthenticated в обработчике исключений вашего приложения, чтобы корректно перенаправить пользователей на страницу входа в систему.

Добавление собственных гвардов

Вы можете определить собственные гварды аутентификации, используя метод extend фасада Auth . Вы должны поместить этот вызов extend внутри сервис-провайдера. Так как в состав Laravel уже входит AuthServiceProvider , можно поместить данный код в провайдер:

Как видите, в этом примере переданная в метод extend анонимная функция должна вернуть реализацию Illuminate\Contracts\Auth\Guard . Этот интерфейс содержит несколько методов, которые вам надо реализовать, для определения собственного гварда. Когда вы определили своего гварда, вы можете использовать его в настройке guards своего конфига auth.php :

Гварды в виде анонимных функций

Функционалом аутентификации можно воспользоваться без создания классов гвардов, при помощи анонимной функции в Auth::viaRequest .

Добавьте Auth::viaRequest в метод boot вашего AuthServiceProvider . В качестве аргументов viaRequest принимает название драйвера аутентификации, который вы определите в функции и собственно саму функцию, которая возвращает экземпляр класса User, залогиненного пользователя, если аутентификация пройдена и null если нет. На вход эта функция принимает экземпляр класса HTTP запроса.

Вот пример аутентификации по токену, который передан в запросе:

Чтобы сообщить приложению, что аутентификацию нужно проводить при помощи драйвера, указанного в viaRequest , укажите его имя в конфиге auth.php в секции guards :

Добавление собственных провайдеров пользователей

Если вы не используете традиционную реляционную базу данных для хранения ваших пользователей, вам необходимо добавить в Laravel свой собственный провайдер аутентификации пользователей. Мы используем метод provider фасада Auth для определения своего провайдера:

После регистрации провайдера методом provider , вы можете переключиться на новый провайдер в файле настроек auth.php . Сначала определите провайдера provider , который использует ваш новый драйвер:

Затем вы можете использовать этот провайдер в вашей настройке guards :

Контракт User Provider

Реализации Illuminate\Contracts\Auth\UserProvider отвечают только за извлечение реализаций Illuminate\Contracts\Auth\Authenticatable из постоянных систем хранения, таких как MySQL, Riak, и т.п. Эти два интерфейса позволяют механизмам аутентификации Laravel продолжать функционировать независимо от того, как хранятся данные пользователей и какой тип класса использован для их представления.

Давайте взглянем на контракт Illuminate\Contracts\Auth\UserProvider :

Функция retrieveById обычно принимает ключ, отображающий пользователя, такой как автоинкрементный ID из базы данных MySQL. Реализация Authenticatable , соответствующая этому ID, должна быть получена и возвращена этим методом.

Функция retrieveByToken принимает пользователя по его уникальному $identifier и ключу $token "запомнить меня", хранящемуся в поле remember_token . Как и предыдущий метод, он должен возвращать реализацию Authenticatable .

Метод updateRememberToken обновляет поле remember_token пользователя $user значением нового $token .

Метод retrieveByCredentials принимает массив авторизационных данных, переданных в метод Auth::attempt при попытке входа в приложение. Затем метод должен "запросить" у основного постоянного хранилища того пользователя, который соответствует этим авторизационным данным. Обычно этот метод выполняет запрос с условием "where" для $credentials[‘username’] . Затем метод должен вернуть реализацию Authenticatable . Этот метод не должен пытаться проверить пароль или аутентифицировать пользователя.

Метод validateCredentials должен сравнить данного $user с $credentials для аутентификации пользователя. Например, этот метод может сравнить строку $user->getAuthPassword() с Hash::check для сравнения значения $credentials[‘password’] . Этот метод должен возвращать true или false , указывая верен ли пароль.

Контракт Authenticatable

Теперь, когда мы изучили каждый метод в UserProvider , давайте посмотрим на контракт Authenticatable . Помните, провайдер должен вернуть реализацию этого интерфейса из методов retrieveById , retrieveByToken , и retrieveByCredentials :

Этот интерфейс довольно прост. Метод getAuthIdentifierName должен возвращать имя поля "первичного ключа» пользователя", а метод getAuthIdentifier — "первичный ключ" пользователя. При использовании MySQL это будет автоинкрементный первичный ключ. Метод getAuthPassword должен возвращать хешированный пароль пользователя. Этот интерфейс позволяет системе аутентификации работать с классом User, независимо от используемой ORM и уровня абстракции хранилища. По умолчанию Laravel содержит в директории app класс User , который реализует этот интерфейс. Вы можете подсмотреть в нём пример реализации.

События

Laravel генерирует различные события в процессе аутентификации. Вы можете прикрепить слушателей к этим событиям в вашем EventServiceProvider :

Laravel 9 Get Current Logged in User Data Example

This post will give you an example of laravel 9 get current logged in user id. Here you will learn how to get the current user id in laravel 9. you’ll learn laravel 9 get current user id. In this article, we will implement a get current user data laravel 9. You just need to some steps to done get the current user email in laravel 9.

In this tutorial, I will give you four ways to get current login user details in the view file and controller file, so let’s see the following examples as below:

1) Laravel 9 Get Current User in Controller using Helper

2) Laravel 9 Get Current User in Controller using Facade

3) Laravel 9 Get Current User in View Blade using Helper

4) Laravel 9 Get Current User in View Blade using Facade

So, let’s see I added two ways to get current user data in the laravel 9 application.

1) Laravel 9 Get Current User in Controller using Helper

Here, we will get current user data using auth() in laravel 9.

2) Laravel 9 Get Current User in Controller using Facade

Here, we will get current user data using Auth facade in laravel 9.

3) Laravel 9 Get Current User in View Blade using Helper

Here, we will get current user data using auth() helper in laravel 9.

4) Laravel 9 Get Current User in View Blade using Facade

Here, we will get current user data using Auth Facade in laravel 9.

I hope it can help you.

Hardik Savani

I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

Вывод всех статьей в профиле авторизованного пользователя

Вывод данных авторизованного пользователя
Здравствуйте, помогите пожалуйста! Есть форма, на которой проходит авторизация. При успешной.

ID авторизованного пользователя
Добрый вечер, ребята просьба о помощи. Работаю с локальной базой данных в первые Мне необходимо.

Запись авторизованного пользователя в БД
У меня такая проблема, я делаю гостевую книгу. Для отправки сообщения пользователю надо.

Подпись авторизованного пользователя в MS Access
Всем доброго времени суток! Вопрос следующий: Есть у меня в табличке поле "Расшифровка подписи".

Сообщение от dmitrygrinevic

В Users модели по идее у тебя должно быть

Ну в миграции должен быть внешний ключ (ты вроде это сделал)

В контроллере ты должен:

1. Получить авторизованного пользователя (что ты сделал)
2. $posts = $user->posts()->get() —> получение
3. return view(‘someview’,compact(‘posts’));

А я бы сделал так —> в index.php просто бы вернул вид, а в самом blade.php

Сообщение от Sneykas

dmitrygrinevic,
Соглашусь, я имел в виду метод контроллера

Controller —> public function index()

Получить имя авторизованного пользователя
Здравствуйте,сайт на joomla 2.5,как достать имя авторизованного пользователя для своего скрипта,и.

Запретить модификацию БД для авторизованного пользователя
Как сделать чтобы при авторизации в программе пользователь не мог изменять базу данных?

Нужно вывести значение авторизованного пользователя
Написал код который выводит значения денег всех зарегистрированных пользователей, а нужно выводить.

Проверка на авторизованного пользователя в php коде
У меня есть код который может проверять пусты ли логин пароль пользователя. есть подключенная БД в.

Редирект авторизованного пользователя со страницы регистрации
Помогите пожалуйста, нужно чтобы сразу после регистрации пользователя перекидывало уже.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *