Authentication and Authorization in Laravel
Authentication:
Authentication is a process or machanism for verifying and checking the identity of a user, system, any information, and device before grant permission and access to a specific information, before allow permission and resources, application or system.
Laravel's authentications facilities are made up of guards and providers.
Guard: It define how users are authenticated for each request.
eg. Laravel ships with a session guard which maintains state using session storage and cookies.
Provider: It define how users are retrieved from your persistaet storage laravel shift with support for retrieving users using Eloquent and database query builder.
However. you can define provider as for accourding your application requirements.
Laravel application's authentication configuration file is located in "config/auth.php"
How authentication works in laravel?
When i am using form for login credential like username and password. If these following credentials true or correct, so application store that information of authenticated user in user's session.
A cookie issued to the browser contains session ID so that the subsequent request 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".
领英推è
Laravel has Built-in Browser Authentication Services
Laravel includes built-in authentication and session services which are typically accessed via the "Auth" and "Session" facades. These feature provide cookie-based authentication for requests that are initiated from web browsers.
Retrieve Authenticated User
You will often need to interact with the currently authencated user. While handling and incoming request, you may access the authenticated user via the "Auth" facade's and "user" method:
use Illuminate\Support\Facades\Auth;
// retrieve the currently authenticated user
$user = Auth::user();
// retrieve the currently authenticated user's ID
$id = Auth::id();
Alternattively, once a user is authenticated, you may access the authenticated user via an "Illuminate\Http\Request;" instance.
Remember, type-hinted classes will be automatically injected into your controller methods.
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function user(Request $request): RedirectResponse
{
$user = $request->user();
}
}
Check the curent user is authenticated
To determine if the user making the incoming HTTP request is authenticated you may use the method "check" on the "Auth" facades. This method return "true" if the user is authenticated:
use Illuminate\Support\Facades\Auth;
if ( Auth::check() ) {
// the user is logged in
}