Laravel basic tutorial-Certification Overview
Laravel makes implementing authentication very simple. In fact, it provides comprehensive configuration items to adapt to the application's business. The authentication configuration file is stored in the config/auth. php Directory. every option here provides a complete annotation document. you can adjust the authentication service behavior from here.
In laravel, the core of the certification service is composed of guards (guard) and providers (suppliers. A guard defines a way to authenticate a user from a request. for example, laravel comes with a session guard and a token guard. session guard authenticates the user in the request from the stored sessions and cookies, the token guard performs user authentication from the API token in the request.
The supplier defines how to get users from persistent storage. Laravel provides two retrieval methods: Eloquent and database query constructor. Of course, you can also add additional suppliers to do this.
Don't worry if this sounds messy. Most applications do not need to modify the default configuration of the authentication service.
Database considerations
By default, laravel contains the app \ User Eloquent model in the App directory. This model uses the default Eloquent authentication driver. If your application does not use the Eloquent driver, you can use the database authentication driver, which is based on the laravel query constructor.
When you build a database table structure for the App \ User model, you should ensure that the password should be at least 60 characters long. the default 255 is a good choice.
In addition, make sure that the users table contains a string column remember_token that can be null. it should have a length of 100 characters. This field is used to store the tokens that the user maintains long-term logon. You can use $ table-> rememberToken () in the migration to quickly add this column.
Quick start
Laravel loads two Controllers for authentication, which are stored in the App \ Http \ Controllers \ Auth namespace. AuthController is used to process the logic of user registration and authentication, while PasswordController contains the logic related to user password retrieval. Each of their controllers includes the methods they need by introducing trait. For most applications, you have no need to modify these controllers.
Routing
Laravel provides a quick way to generate authentication routing and view scaffolding. you can use the artisan command:
php artisan make:auth
In a new application, this command is used to install, register, and log on views, and inject all authentication-Related routes. HomeController will also be generated. This controller provides the post login request processing method. You can also delete or modify the controller as needed.
View
As mentioned above, the php artisan make: auth command creates all authentication-related views and stores them in the resources/views/auth directory.
The make: auth command also creates the resoucres/views/layouts directory and creates a basic layout for the application. All of these views use the Bootstrap CSS framework. you can customize the modifications as needed.
Perform authentication
Now you have the controller, route, and view related to authentication, and your application has the ability to register and authenticate. You can access your application through a browser. the authentication controller includes all authenticated users and methods for storing users to the database (through traits ).
Custom redirect address
After authentication, the user will be redirected to/URL. You can modify the redirection address by defining the redirectTo attribute in the AuthController controller:
protected $rediredtTo = '/home';
If the user fails to authenticate, it will redirect back to the logon address.
Custom Guard
You can also customize guard to verify users. You need to define the guard attribute in AuthController. Its value should match a guards value in your auth. php configuration:
protected $guard = 'admin';
Custom Verification/storage
You may want to store some other necessary form fields during user registration and store new user information in the database. at this time, you need to modify the AuthController class, this class is used to create and verify the form.
Use the validate method in the AuthController class to verify the matching degree between the form and the validation rule. You can modify this method as needed.
Use the create method in the AuthController class to add a user record to the database. Eloquent ORM is used here. You can modify this method as needed.
Obtain authenticated users
You can access authenticated users through the Auth mask:
$user = Auth::user();
In addition, once the user is verified, you can access the authenticated user through the Illuminate \ Http \ Request instance. You should remember that the class of the type prompt will be automatically injected into your controller method:
user()) { // $request->user() returns an instance of the authenticated user... } }}Determine whether the current user has been authenticated
You can use the Auth check method to determine whether the current user has been authenticated. If the user has been authenticated, true is returned:
if (Auth::check()) { // The user is logged in...}
You should use middleware to filter unauthenticated users to access certain routes or controllers.
Protect routes
Routing middleware can be used to limit that only authenticated users can access the specified route. Laravel comes with the auth Middleware, which is defined in the app \ Http \ Middleware \ Authenticate. php file. You only need to attach the middleware to define the route:
// Using A Route Closure...Route::get('profile', ['middleware' => 'auth', function () { // Only authenticated users may enter... }]);// Using A Controller...Route::get('profile', [ 'middleware' => 'auth', 'uses' => 'ProfileController@show']);
Of course, if you use a controller to register a route, you can use the middleware method in the controller constructor to attach the middleware:
public function __construct(){ $this->middleware('auth');}Specified guard
When you attach the auth middleware to the route, you can also specify which guard to choose to provide authentication:
Route::get('profile', [ 'middleware' => 'auth:api', 'uses' => 'ProfileController@show']);
The specified guard should match one of the guards array keys in the configuration file auth. php.
Authentication and throttling
If you use the AuthController class created in laravel, Illuminate \ Foundation \ Auth \ ThrottlesLogins trait can be used to limit the number of user attempts to log on. By default, when a user fails to log on several times, the user cannot log on within one minute. The throttling is determined based on the user's username/email and IP address:
Manual user authenticationOf course, you do not have to use the authentication controller built in laravel. If you choose to delete these authentication controllers, you need to directly use the laravel authentication class to manage user authentication. Don't worry, of course.
We will access laravel's authentication service through the Auth mask. Therefore, we need to ensure that the Auth mask is introduced at the top of the class file. Next, let's take a look at the attempt method:
$email, 'password' => $password])) { // Authentication passed... return redirect()->intended('dashboard'); } }} The attempt method receives an array of key-value pairs as the first parameter. The values in the array are used to find matched users in the database. Therefore, in the above example, a user matching the email column $ email will be returned. If the user is found, the hash password stored in the database matches the hash-encrypted password value in the array. If the two hash values match successfully, a user-authenticated session is enabled.
If the authentication succeeds, the attempt method returns true. Otherwise, false is returned.
The intended method is used to return the URL address to be accessed by the redirector before logon. this method also receives a parameter as the standby address when the requested address is unavailable.
Specify additional authentication informationIf you need it, you can add some additional conditions for authentication query. for example, you need to verify the user marked as 'active:
if (Auht::attempt(['email' => $email, 'password' => $password, 'active' => 1])) { // The user is active, not suspended, and exists.}
Note: In the preceding example, email is not a required option. this is just an example. You can use any credential for user authentication to map fields in the database.
Access a specified protected instanceYou can use the Auth counterfeit guard method to obtain the desired guard instance. This allows you to manage multiple authentication models or user tables in the same application and implement independent authentication.
The name of the guard passed in the guard method should match one of the guards in the configuration file auth. php:
if (Auth::guard('admin')->attempt($credentials)) { //}LogoutYou can use the Auth fake logout method to exit a user. this method will clear the user authentication session information:
Auth::logout();
Remember usersIf you want to provide the Remember Me function in your application, you only need to pass a Boolean value in the attempt method as the second parameter, this will keep the user authentication information until the user logs out manually. Of course, this requires that your user table contain the remember_token column:
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) { // The user is being remembered...} If you log on as a remembered user, you can use the viaRemember method to determine whether the user authentication has passed my cookie:
if (Auth::viaRemember()) { //}Other authentication methods are authenticated by user instances.If you need to record an existing user instance in the application, you can use the login method. The given parameter must be an instance that implements the Illuminate \ Contracts \ Auth \ Authenticatable contract. Of course, in laravel, the App \ User model has implemented this interface:
Auth::login($user);
Of course, you can also specify the instance guard:
Auth::guard('admin')->login($user);Directly authenticated by user IDYou can use the loginUseingId method to record user information by ID. this method simply receives a primary key of the user to be authenticated:
Auth::loginUsingId(1);
Only authenticate the user onceThe once method performs user authentication only in the current request. Session or cookies are not stored. This is helpful for building stateless APIs. The once method and attempt have the same visa method:
if (Auth::once($credentials)) { //}HTTP-based authenticationHTTP-based authentication provides a fast user authentication mechanism without setting up a dedicated logon page. To get started, you should attach the auth. basic middleware to your route. The auth. basic middleware is built in laravel, so you do not need to define it:
Route::get('profile', ['middleware' => 'auth.basic', function () { // Only authenticated users may enter... }]); Once the middleware is attached to a route, authentication information is prompted every time you access the route. By default, auth. basic middleware uses the email column as the user name recorded by the user.
FastCGI promptIf you use PHP FastCGI, HTTP-based authentication may not work properly. You can try to add the following content to the. htaccess file:
RewriteCond %{HTTP:Authorization} ^(.+)$RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]Stateless basic HTTP authenticationYou can also save the user's identity to the cookie without using session when using HTTP basic authentication. This is particularly effective in API-based authentication. To do this, you can define a middleware and then call the onceBasic method. If the onceBasic method does not return a response, the request will be further transmitted to the application:
Next, add the middleware to the route:
Route::get('api/user', ['middleware' => 'auth.basic.once', function () { // Only authenticated users may enter... }]); Of course, you also need to register the middleware in the kernel. php core.
Considerations for database password resetMost applications provide a way for users to reset their forgotten passwords. Laravel provides a convenient way to send password prompts and provide password reset, so that you do not need to be forced to implement this mechanism in every application.
To help you get started, make sure that your App \ User model has implemented the Illuminate \ Contracts \ Auth \ CanResetPassword contract. The App \ User model in laravel has implemented this excuse, illuminate \ Auth \ Passwords \ CanResetPassword trait is used.
Generate a password reset table through migration
Next, you must create a table to store tokens for password resetting. Laravel already provides table migration and stores it in the database/migrations Directory. Therefore, you only need to execute the migration command:
php artisan migrate
RoutingThe Auth \ PasswordController controller provided by laravel contains all the logic required to reset the password. All the routes that provide password reset can be generated using the make: auth Artisan command:
php artisan make:auth
ViewWhen the make: auth command is executed, laravel generates the view required for resetting all passwords. These views will be stored in the resources/views/auth/passwords Directory. you can modify them as needed.
After resetting the passwordOnce you have generated all the routes and views required to reset the password, you can reset the password by accessing/password/reset routes in the browser. PasswordController already contains the function of sending a link email for resetting the password and updating the password to the database.
After the password is reset, the user will automatically log on and be redirected to/home. You can define the redirectTo attribute in PasswordController to customize the redirect address:
protected $redirectTo = '/dashboard';
Note: By default, the token for password resetting is only valid for one hour. you can modify the expire option in the config/auth. php configuration file.
CustomizationCustom authentication guard
In the auth. php configuration file, you can configure multiple "guards" to perform authentication actions on various user tables. You can use the $ guard attribute in PasswordController to select the guard:
/** * The authentication guard that should be used. * * @var string */ protected $guard = 'admins';
Customized password broker
In the auth. php configuration file, you can configure multiple passwords "brokers" to reset passwords in multiple user tables. You can select by adding the $ broker attribute in PasswordController:
/** * The password broker that should be used. * * @var string */ protected $broker = 'admins';
Add custom guardYou can use the extend method of the Auth mask in the service container to define your own authentication guard:
You should be able to see from the above example that you should return an implementation of Illuminate \ Contracts \ Auth \ Guard in the extend method. To customize the guard, you need to implement the methods included in this interface.
Once your guard is defined, you can configure it in the guards option of the auth. php configuration file:
'guards' => [ 'api' => [ 'driver' => 'jwt', 'provider' => 'users' ],];
Add custom user providersIf you do not use traditional relational databases to store your users, you need to provide your own user provider to expand laravel. You can define your own user provider by using the Auth dummy provider method. You should call this method in the service provider:
After you use the provider method to register the provider, you need to switch your user provider to the newly registered provider in the config/auth. php configuration file:
'providers' => [ 'users' => [ 'driver' => 'riak', ],],
Then, you need to use the provider in the guards option:
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ],],
User provider contractThe implementation of Illuminate \ Contracts \ Auth \ UserProvider only manages how to obtain an Illuminate \ Contracts \ Auth \ Authenticatable implementation from the persistent storage system. Such as MySQL and Riak. These two interfaces implement laravel's continuous authentication mechanism without considering where user data is stored or what type of data is stored.
Let's take a look at the Illuminate \ Contracts \ Auth \ UserProvider contract:
The retrieveById method is used to receive a key to return a user, for example, the auto-increment primary key ID of the MySQL database. The matched ID should return an implementation of Authenticatable.
The retrieveByToken method receives the $ token of "Remember Me" stored by the unique identifier $ identifier and remember_token used to identify a user. Like the above method, this method should return an implementation of Authenticatable.
The updateRememberToken method uses the new $ token to update the user's remember_token field. This new field can be allocated when the user logs on successfully and sets remember me. it can also be null allocated after the user logs out.
The retrieveByCredentials method receives an array credential, which is passed to the Auth: attemp method when the user attempts to log on. This method will query the matching status of the underlying persistent storage device creden。. Generally, this method uses the where condition statement to query similar matching conditions of $ credentials ['username. This method should return the implementation of a UserInterface.Do not perform password verification or authentication in this method.
The validateCredentials method should compare the matching conditions of the given user and credential. For example, this method may compare $ user-getAuthPassword () and $ credentials ['password'] After Hash: make. This method should only verify the effect between users and creden。 and return a Boolean value for comparison.
Authenticatable contractWe have discussed all the methods in UserProvider. now let's take a look at the Authenticatable contract. you should remember that the provider should return the implementation of this contract interface from the retrieveById and retrieveByCredentials methods:
This interface is relatively simple. The getAuthIdentifierName method should return the name of the user's primary key field. The getAuthIdentifier method should return the user's primary key. In MySQL, this primary key is generally a self-increasing primary key value. GetAuthPassword should return the user's hash password. This interface enables the authentication system to run in any user class without worrying about what ORM or other storage abstraction layer you are using. By default, laravel contains the User class in the app directory, which implements this contract. So you can refer to the implementation method of this class.
EventLaravel provides various events in the authentication process. You can append the listener to your EventServiceProvider:
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'Illuminate\Auth\Events\Attempting' => [ 'App\Listeners\LogAuthenticationAttempt', ], 'Illuminate\Auth\Events\Login' => [ 'App\Listeners\LogSuccessfulLogin', ], 'Illuminate\Auth\Events\logout' => [ 'App\Listeners\logSuccessfulLogout', ], 'Illuminate\Auth\Events\Lockout' => [ 'App\Listeners\LogLockout', ], ];