”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Laravel Auth 路由教程

Laravel Auth 路由教程

发布于2024-11-06
浏览:970

Laravel auth routes is one of the essential features of the Laravel framework. Using middlewares you can implement different authentication strategies and attach them to different parts of your backend.

Laravel offers a complete and flexible authentication system, capable of adapting to various needs and implementations. There are also several external packages to implement additional authentication processes other than what ship with the framework by default.

In this article I show you the implications of the standard authentication system and other auth routes systems I navigated in the last ten years of experience with Laravel.

Authentication Guards e Providers in Laravel

The logic behind routes authentication in Laravel is based on the implementation of two different objects:

  • Guard: defines how to determine whether an HTTP request is coming from an authenticated user;
  • Provider: defines how to retrieve registered users for the application. You can check out these configurations in the config/auth.php configuration file.
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
*/
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],
/*
|----------------------------------------------------------------------
| User Providers
|----------------------------------------------------------------------
|
*/

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => \App\Domains\Organization\Models\User::class,
    ],
],

A newly created Laravel application provides a default guard and provider configuration suited to the needs of an application that only delivers web pages and generates the HTML of its pages entirely on the server side.

The default guard is “session” – which uses session cookies to establish whether the request comes from an authenticated user – and the default provider is the “database” that retrieves the registered users information via Eloquent.

If you are not using a traditional relational database to store your users, you can extend Laravel with your own authentication user provider. Here is an example from the official documentation:

make('mongo.connection'));
        });
    }
}

Than you can change the default provider in the configuration file:

'providers' => [
    'users' => [
        'driver' => 'mongo',
    ],
],

Finally, you must reference this new provider in the guards configuration:

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

There are many situations where the default configuration is not enough. For example, the case in which your application offers RESTful APIs or if it’s the backend of a Single Page Application. In this case, you need to include and configure other authentication services offered by the Laravel ecosystem.

For example, in the case of the API server, you should opt for a token-type guard, which allows you to recognize clients authenticated by a specific token present in the request. Personally I use a Laravel first-party package called Passport that implements a complete OAuth server so I can manage authentication for frontend and backend API with the same framework and a very granular logic.

User eloquent model as authentication provider

It's not a coincidence that the App\Models\User class does not directly extend the basic Eloquent Model class, but the Illuminate\Foundation\Auth\User class. This allows us to identify it as an appropriate model to be a provider for the users of the application.

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];
}

Check if a session is authenticated

HTTP requests coming from a client that has successfully completed authentication can be spotted at various points in the stack. This allows you to intervene in appropriate ways to prevent certain actions or modify the application behaviors accordingly.

You can perform this check in controllers, views and even routes. Both individual endpoints and grouped routes.

The best way to enforce mandatory authentication on endpoints is using middleware. Laravel provides two built-in middlewares:

  • guest – for routes accessible from unauthenticated clients;
  • auth – for routes accessible only by authenticated users;

These middlewares are available as "route-specific" middlewares and can therefore be applied to each route, independently of any other middleware.

Navigate to the App\Http\Kernel class or in the bootstrap/app.php file inside the withMiddleware() method.

/**
* The application's route middleware.
*
* These middlewares may be assigned to groups or used individually.
*
* @var array
*/
protected $middlewareAliases = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

    ...
];

You can use them to control access to your routes:

// The home page is accessible to everyone
Route::get('/', [WebsiteController:class, 'home']);

// Register routes are accessible only to unauthenticated users
Route::get('/register', [RegisterController::class, 'create'])
    ->name('register')
    ->middleware('guest');

Route::post('/register', [RegisterController::class, 'store'])
    ->middleware('guest');

// Dashboard is accessible only to authenticated users
Route::get('/dashboard', [DashboardController::class, 'home'])
    ->middleware('auth');

The difference between GUEST and AUTH route middlewares

The "guest" middleware is used to restrict access to certain routes or actions to unauthenticated users only.

Restrict access to unauthenticated users?

Yes, in fact as you can see in the snippet above the class associated with the guest middleware is "RedirectIfAuthenticated".

So guest allows you to make the routes accessible if you are a “free” user, but the moment you authenticate to the website Laravel will redirect you to the "private" section of the application. You can’t navigate "guest routes" if you are authenticated.

In a nutshell, "guest" is useful for the registration page, not in an e-commerce product page :).

The purpose of the auth middleware, however, is not at all ambiguous. It checks if the current Request is authenticated. Otherwise you are redirected to the public section of the application, such as the login page.

Authentication In Laravel Blade Template

At this point, you may want to change the behavior of some of your application pages to show different content depending on whether it is a visitor or an authenticated user. To do this, we can use the @auth directive:

@auth
    Welcome {{ auth()->user()->name }}
@else
    Login
    Register
@endauth

The @auth and @guest directives operate like an if statement, thus allowing portions of the view to be rendered if the rendering of the view is requested by an authenticated user or a visitor respectively.

How to get the authenticated user

Laravel provides you with a built-in service called "Auth" that allows you to operate transparently with the underlying user providers and guards.To access the Auth service you can use the Facade Illuminate\Support\Facades\Auth, or the helper function auth().

use Illuminate\Support\Facades\Auth;

// Access the authenticated User instance
$name = Auth::user()->name;
$name = auth()->user()->name;

// Check if the current session is authenticated
if (Auth::check()) {
    // User logged in
}

Logout: Terminate an authenticated session in Laravel

In your routes/web.php you should have the logout route:

Route::get('logout', [LoginController::class, 'logout')->middleware('auth');

In the LoginController.php

public function logout(Request $request) 
{
    Auth::logout();
    return redirect('/login');
}

Now, you are able to logout using yourdomain.com/logout URL or if you have created a logout button, add href to "/logout".

The logout method will clear the authentication information in the user’s session.

Logout other devices

Invalidating sessions on other devices Laravel also provides a mechanism for invalidating and "logging out" user sessions that are active on other devices without invalidating the session on their current device. This feature is typically used when a user changes or updates their password and you want to invalidate sessions on other devices while maintaining the authenticity of the current device.

To implement this feature Laravel provides a built-in middleware that you should add to the “web” middleware group: \Illuminate\Session\Middleware\AuthenticateSession

'web' => [
    // ...
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    // ...
],

Once the middleware is attached you can use the logoutOtherDevices() method on the Auth service.

use Illuminate\Support\Facades\Auth;

public function logoutOtherDevices(Request $request)
{
    $password = $request->input('password');

    if (Hash::check($password, Auth::user()->password)) {
        Auth::logoutOtherDevices($password);

        // Optionally, you can regenerate the user's session ID
        $request->session()->regenerate();

        return redirect()->back()->with('success', 'Logged out from other devices successfully.');
    }

    return redirect()->back()->withErrors(['password' => 'Invalid password.']);
}

After the logoutOtherDevices method is executed, the user remains logged in on the current device, but all other sessions associated with that user are terminated. When the user tries to access the application from other devices, they will be required to log in again.After logging out from other devices, you can optionally regenerate the user's session ID using $request->session()->regenerate() to further enhance security.

You can follow me on Linkedin or X. I post about building my SaaS product.

Monitor your PHP application for free

Inspector is a Code Execution Monitoring tool specifically designed for software developers. You don't need to install anything at the server level, just install the composer package and you are ready to go.

Inspector is super easy and PHP friendly. You can try our Laravel or Symfony package.

If you are looking for HTTP monitoring, database query insights, and the ability to forward alerts and notifications into your preferred messaging environment, try Inspector for free. Register your account.

Or learn more on the website: https://inspector.dev

Laravel Auth Routes Tutorial

版本声明 本文转载于:https://dev.to/inspector/laravel-auth-routes-tutorial-hm3?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何在 Go 中跟踪 HTTP POST 请求的进度?
    如何在 Go 中跟踪 HTTP POST 请求的进度?
    Go 中跟踪 HTTP POST 请求的进度通过 POST 请求发送大文件和图像时,开发者经常面临跟踪上传进度的挑战。本问题探讨了一种可靠的方法来监控 Go 应用程序中此类请求的进度。该问题建议手动打开 TCP 连接并分块发送 HTTP 请求。但是,此方法可能会遇到 HTTPS 站点的限制,并且不被...
    编程 发布于2024-11-06
  • 如何在 Java 中获取文件夹中的文件名列表?
    如何在 Java 中获取文件夹中的文件名列表?
    使用 Java 获取文件夹中的文件名获取目录中文件名列表的任务是各种环境中的常见需求编程场景。要在 Java 中实现此目的,有一种简单的方法,即利用 File 类。代码方法:首先,使用所需的目录路径实例化 File 对象:File folder = new File("your/path&...
    编程 发布于2024-11-06
  • 角管:综合指南
    角管:综合指南
    Angular 中的 Pipes 是简单的函数,用于在不修改底层数据的情况下转换模板中的数据。管道接收一个值,对其进行处理,然后返回格式化或转换后的输出。它们通常用于格式化日期、数字、字符串,甚至数组或对象。 它们允许您直接在视图中以更具可读性或相关性的格式格式化和显示数据,而无需更改底层数据模型。...
    编程 发布于2024-11-06
  • Tailwind CSS 和深色模式
    Tailwind CSS 和深色模式
    在本文中,我们将探讨如何在 Tailwind CSS 中实现深色模式。深色模式已成为流行的设计趋势,因为它可以在低光环境下提供更好的用户体验并减轻眼睛疲劳。 Tailwind 可以通过其内置实用程序轻松支持暗模式。 1. Tailwind 中的深色模式如何工作 Tailwind 提供...
    编程 发布于2024-11-06
  • 如何使用 CakePHP 的 Find 方法执行 JOIN 查询?
    如何使用 CakePHP 的 Find 方法执行 JOIN 查询?
    CakePHP Find 方法与 JOINCakePHP find 方法提供了一种从数据库检索数据的强大方法,包括连接表。本文演示了使用 CakePHP 的 find 方法执行 JOIN 查询的两种方法。方法 1:利用模型关系此方法涉及定义模型之间的关系并使用可遏制的行为。考虑以下模型关系:clas...
    编程 发布于2024-11-06
  • 如何在 Python 中重用生成器而不重新计算或存储结果?
    如何在 Python 中重用生成器而不重新计算或存储结果?
    通过重置在 Python 中重用生成器在 Python 中,生成器是用于迭代元素序列的强大工具。但是,一旦迭代开始,生成器就无法倒回。如果您需要多次重用生成器,这可能会带来挑战。重用生成器的一个策略是再次重新运行生成器函数。这将从头开始重新启动生成过程。然而,如果生成器函数的计算成本很高,则这种方法...
    编程 发布于2024-11-06
  • 面向 JavaScript 开发人员的热门 S 代码扩展
    面向 JavaScript 开发人员的热门 S 代码扩展
    JavaScript 正在快速发展,围绕它的工具生态系统也在快速发展。 作为开发人员,您希望使您的工作流程尽可能高效和流畅。这就是 Visual Studio Code (VS Code) 的用武之地。 我精心挑选了 5 个 VS Code 扩展,它们将显着增强您的 JavaScript 开发体验。...
    编程 发布于2024-11-06
  • 如何使用 HTML 输出标签来显示计算结果。
    如何使用 HTML 输出标签来显示计算结果。
    欢迎回来!我希望每个人都度过愉快的周末。今天,让我们回到 HTML 标签并重点关注 标签。 标签是什么? 标签用于显示计算结果。它是一个内联元素,可以放置在 、 或其他内联元素内。它通常用于显示计算结果或实时显示变量值。 阅读完整文章,实时观看并获取代码。 ...
    编程 发布于2024-11-06
  • Java:理解变量、数据类型和输入/输出
    Java:理解变量、数据类型和输入/输出
    介绍: Java 是世界上最流行、最通用的编程语言之一,它被用于从 Web 应用程序到移动应用程序的所有领域。如果您要开始 Java 之旅,了解基础知识至关重要。在本指南中,我们将深入探讨三个基本概念——变量、数据类型和输入/输出操作——它们构成了任何 Java 程序的支柱。在读完...
    编程 发布于2024-11-06
  • 如何根据 Div 的高度保持其纵横比?
    如何根据 Div 的高度保持其纵横比?
    根据高度维护 Div 的长宽比在网页设计中,控制元素的长宽比对于响应式布局至关重要。本题探讨了如何保持 div 的宽度占其高度的百分比,确保元素的形状保持一致,无论其高度如何变化。传统方法是使用 padding-top 来设置 div 的高度一个元素,而 padding-left 可以用作对象宽度的...
    编程 发布于2024-11-06
  • 在 Flet 中处理 DatePicker
    在 Flet 中处理 DatePicker
    我需要执行 DatePicker 的项目。 Veamos el ejemplo que proporciona la documentación oficial de Flet. import datetime import flet as ft def main(page: ft.Page): ...
    编程 发布于2024-11-06
  • 如何调整图像大小以适合圆形 SVG 蒙版?
    如何调整图像大小以适合圆形 SVG 蒙版?
    调整图像大小以适合圆形 SVG 路径尝试使用 SVG 路径从图像中剪切圆形部分时,这一点很重要以确保正确对齐。如果图像不太适合,可能是由于 SVG 蒙版的大小或位置不正确。这里有一种实现所需结果的替代方法:使用增强SVG 蒙版:此方法使用 SVG 蒙版创建一个圆孔,在其中显示图像:<svg w...
    编程 发布于2024-11-06
  • 技术面试问题 - 部分打字稿
    技术面试问题 - 部分打字稿
    Introduction Hello, hello!! :D Hope you’re all doing well! How we’re really feeling: I’m back with the second part of this series. ? In this...
    编程 发布于2024-11-06
  • 如何在 Laravel Eloquent 中为每个唯一的“seller_id”选择具有最大“created_at”的行?
    如何在 Laravel Eloquent 中为每个唯一的“seller_id”选择具有最大“created_at”的行?
    Laravel Eloquent: Select Rows with Maximum Created_at在 Laravel Eloquent 中,你可能会遇到需要选择所有具有最大值的行的场景表中每个唯一的 seller_id 的created_at 值。以下是实现此目的的方法:使用原始 SQL 查...
    编程 发布于2024-11-06
  • ReactJS 中的延迟加载:开发人员指南
    ReactJS 中的延迟加载:开发人员指南
    延迟加载是 ReactJS 中一项强大的技术,它允许组件或元素仅在需要时才加载,从而增强了 Web 应用程序的性能。在本文中,我们将探讨延迟加载的概念、它的好处,以及如何使用内置的 React.lazy() 和 React.Suspense 特征。   什么是延迟加载? 延迟加载是W...
    编程 发布于2024-11-06

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3