Home >PHP Framework >Laravel >How Laravel authenticates

How Laravel authenticates

PHPz
PHPzOriginal
2023-04-13 18:12:081251browse

Laravel is one of the most popular PHP frameworks currently. It provides many features, but the most commonly used ones are user authentication and authorization. Laravel provides a rich yet simple authentication system that can be easily integrated into any Laravel application. This article will introduce how Laravel performs authentication.

Basic concepts of Laravel authentication

Laravel authentication provides many available routes and methods to handle login, registration, logout and other operations. Before discussing more details, we need to understand the basic concepts of Laravel authentication.

User Model: Laravel uses the User model to represent users. Creating a User model in Laravel is very simple, just execute the artisan command: php artisan make:model User

Guard: In Laravel, guard is a name , used to specify a specific authentication layer, such as web or api.

Service Provider: Service Provider is one of the most basic components in the Laravel framework. Each service provider is used to register services or bind interfaces and implementations.

Authentication Provider: The authentication provider is the real implementer of authentication. Laravel uses the EloquentAuthenticationProvider by default, which uses a User model to authenticate user credentials.

How to Authentication with Laravel

Now that we have understood the basic concepts of Laravel authentication, we can start introducing how to authenticate in Laravel. There are several steps for authentication in Laravel:

Step 1: Configure Guard

To start using Laravel authentication, you first need to configure Guard in the config/auth.php file. Guard allows you to specify different authentication configurations in your application, such as web authentication and api authentication. Laravel pre-defines the following Guard:

  • web: for session-based web applications.
  • api: for stateless API.

Configuring Guard is a simple process. Find the guards array in the config/auth.php file and add the following content:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

In the above code, we define two Guards: web and api.

Step 2: Define the authenticated User Model

Laravel requires a User model for verification. If you use Laravel's default configuration, you already have a model called User, so no need to define it. In other cases, you need to specify a table and authentication fields for the User model.

protected $table = 'your_user_table_name';

public function getAuthPassword()
{
    return $this->your_password_column_name;
}

Step 3: Create authentication routes

In the web.php file, you can quickly create a set of authentication routes. This set of routes will provide operations such as registration, login, and logout. The following code example demonstrates how to create an authentication route in Laravel:

Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

Step 4: Generate the authentication controller

Now you need to create the controller for the authentication route. You can quickly create a default controller and route using the make:auth Artisan command. This will create the following file:

  • app/Http/Controllers/Auth/LoginController.php
  • app/Http/Controllers/Auth/RegisterController.php
  • app /Http/Controllers/Auth/ResetPasswordController.php
  • app/Http/Controllers/Auth/ForgotPasswordController.php
  • resources/views/auth/login.blade.php
  • resources/views/auth/register.blade.php
  • resources/views/auth/passwords/email.blade.php
  • resources/views/auth/passwords/reset.blade.php

Now you can make appropriate customizations in these controllers and views.

Step 5: Set up Authentication Provider

AuthenticationProvider is a class used to verify user credentials. In Laravel, EloquentAuthenticationProvider is used by default. Specify a User model and authentication fields for your authentication provider.

protected $model;

public function __construct(User $model)
{
    $this->model = $model;
}

public function retrieveById($identifier)
{
    return $this->model->find($identifier);
}

public function retrieveByCredentials(array $credentials)
{
    return $this->model->where('email', $credentials['email'])->first();
}

public function validateCredentials(UserContract $user, array $credentials)
{
    return Hash::check($credentials['password'], $user->getAuthPassword());
}

The above code is the default EloquentAuthenticationProvider provider, and you can customize it based on this. Of course, you can also implement your own Provider.

Step 6: Use the Auth facade for authentication

In Laravel, you can use the Auth facade to implement user authentication. With Auth verification, you can easily check if the user is logged in, authenticated, etc.

Detect whether you have logged in

if (Auth::check()) {
    // 已经登录,继续操作
} else {
    // 未登录,跳转到登录页面
    return redirect('login');
}

Perform authentication

$credentials = [
    'email' => $email,
    'password' => $password,
];

if (Auth::attempt($credentials)) {
    // 验证成功
} else {
    // 验证失败
}

Log out

Auth::logout();

After completing all the steps, you can implement user authentication in Laravel . Now that you have mastered Laravel's main authentication concepts and processes, you can use it to provide strong yet simple user authentication for your own applications.

The above is the detailed content of How Laravel authenticates. For more information, please follow other related articles on the PHP Chinese website!

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