Laravel Basic Tutorial--Certification

Source: Internet
Author: User

Brief introduction

Laravel makes implementing certification very simple, in fact, it provides very comprehensive configuration items to suit the business of the application. The certified configuration file is stored in the config/auth.php directory, where each option provides a complete annotated document where you can adjust the behavior of the authentication service.

In Laravel, the core of the authentication service is composed of guards (guard) and providers (supplier). The guard defines the way the user is authenticated from the request, for example, Laravel has a session guard and token guard, the session guard is the user who authenticates the request from the stored sessions and cookies, and the token guard is the API token from the request For user authentication.

Vendors define how to get users from persistent storage. Laravel itself provides two kinds of retrieval methods for eloquent and database query constructors. Of course, you can also add additional suppliers to do this.

If this sounds confusing, please don't worry. Most applications do not need to modify the default configuration information for the authentication service at all.

Database considerations

By default, Laravel contains the App\user eloquent model in the app directory. The model uses the default eloquent authentication driver. If your application is not using the eloquent driver, you can use the database authentication driver, the database authentication driver is based on the Laravel query Builder.

When you build a database table structure for the App\user model, you should confirm that the password should be at least 60 characters long, and the default of 255 is a better choice.

In addition, you need to make sure that the Users table contains a nullable string column Remember_token, which should have a length of 100 characters. This field is used to store the token value that the user keeps logged in for a long time. You can use $table->remembertoken () in the migration to quickly add the column.

Quick Start

The Laravel loaded two controllers for authentication, which are stored under the App\http\controllers\auth namespace. Authcontroller is used to handle the logic of user registration and authentication, and Passwordcontroller contains the relevant logic to retrieve the user's password. Each of these controllers contains the methods they need by introducing trait. For most applications, there is absolutely no need for you to modify these controllers.

Routing

Laravel provides a quick way to generate certified routes and views of scaffolding that you can use with the artisan command:

PHP Artisan Make:auth

In a new application, this command will be used to install the registration and login views, and will inject all the authentication-related routes. HomeController will also be generated. This controller provides a way to handle post login requests. You can also delete or modify the controller according to your needs.

View

As mentioned above, the PHP artisan make:auth command creates all the authentication-related views and is saved in the Resources/views/auth directory.

The Make:auth command also creates a resoucres/views/layouts directory and creates a basic layout for the app in that directory. All of these views are using the Bootstrap CSS framework, and you can customize the changes to your needs.

For certification

Now that you have certification-related controllers, routes, and views, your app has the ability to enroll and certify. You can access your app through a browser, and the authentication controller already contains all the authenticated users and the method of storing the user to the database (via traits).

Custom REDIRECT Address

The user is redirected to the/URL when authenticated. You can modify the redirect address by defining the Redirectto property in the Authcontroller controller:

protected $rediredtTo = ' home ';

When the user is not authenticated successfully, it redirects back to the login address.

Custom Guard

You can also customize the guard to authenticate users. You need to define the Guard property in Authcontroller. Its value should match one of the guards values in your auth.php configuration:

Protected $guard = ' admin ';

Custom Validation/Storage

You may want to store some other necessary form fields when the user registers, and then store the information of the new user in the database, you need to modify the Authcontroller class, the class supervisor user's creation and the form validation.

Use the Validate method in the Authcontroller class to verify how the validation form matches the validation rule. You can modify this method according to your own needs.

Use the Create method in the Authcontroller class to add a user's record to the database. The eloquent ORM is used here. You can modify this method according to your own needs.

Get Authenticated Users

You can access authenticated users through the Auth mask:

$user = Auth::user ();

In addition, once the user has been authenticated, you can access the authenticated user through an instance of Illuminate\http\request. You should remember that the type hint class is automatically injected into your controller method:

 
  User ()) {       //$request->user () returns an instance of the authenticated user ...}}   

Determine if the current user has been authenticated

You can use the Auth mask check method to determine whether the current user has been authenticated. Returns true if the user has already been authenticated:

if (Auth::check ()) {  //the user is logged in ...}

You should use middleware to filter unauthenticated users to access certain routes or controllers.

Securing Routes

Routing middleware can be used to restrict access to a given route only to authenticated users. Laravel has its own auth middleware, which is defined in the app\http\middleware\authenticate.php file. All you need to do is attach the middleware when defining the route:

Using A Route Closure ... Route::get (' profile ', [' middleware ' = ' auth ', function () {  //* * 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's constructor to attach the middleware:

Public Function __construct () {  $this->middleware (' auth ');}

Designated guard

When you attach auth middleware to routing, you can also specify which guard to choose to provide authentication:

Route::get (' profile ', [  ' middleware ' = ' auth:api ',  ' uses ' = ' profilecontroller@show ']);

The guard specified should match one of the Guards array keys in the configuration file auth.php.

Authentication throttling

If you use the Laravel Authcontroller class, then illuminate\foundation\auth\throttleslogins trait can be used to limit the number of times a user attempts to log in. By default, when a user fails to log in several times, it will not be able to log in for a minute. Throttling is determined by the user's username/e-mail and IP address:

    

User authentication by hand

Of course, you do not necessarily have to use the Laravel built-in authentication controller. If you choose to remove these authentication controllers, then you need to use the Laravel authentication class directly to manage user authentication. Don't worry, it's certainly a cinch.

We will access the Laravel authentication service through the Auth mask, so we want to make sure 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 values as the first parameter. The values in the array are used to find the matching user in the database. So, in the example above, we will return a match to the email listed as $email user. If the user is found, the hashed password stored in the database matches the hashed password value in the array. If the value of the two hashes matches successfully, a session that the user has authenticated will be opened.

If the authentication succeeds, the attempt method returns true. Otherwise, false is returned.

The intended method is used to return to the URL address that the redirector user wants to go to before logging in, and the method also receives a parameter as an alternate address when the requested address is not available.

Specify additional authentication information

If you need to, you can also add some additional criteria to do authentication queries, for example, you need to verify that the user is labeled ' Active ':

if (auht::attempt ([' email ' = = $email, ' password ' = ' + ' $password, ' active ' + 1])) {  //the user is active, not Suspended, and exists.}

Note that email is not an essential option in the example above, just as an example. You can use any credential that authenticates the user to map the fields in the database.

Access to the specified guard instance

You can use the Auth mask guard method to get the instance of the guard you need. This allows you to manage multiple authentication models or user tables in the same application and achieve independent authentication.

The guard name passed in the Guard method should match one of the guards in the configuration file auth.php:

if (Auth::guard (' admin ')->attempt ($credentials)) {  //}

Log out

You can use the Auth mask's Logout method to exit the user, which clears the user-authenticated session information:

Auth::logout ();

Remember users

If you want to provide the ability to remember me in your app, you only need to pass a Boolean value in the attempt method as the second parameter, which will keep the user's authentication information until the user exits the login manually. Of course, this requires that your user table must contain the Remember_token column:

if (auth::attempt ([' Email ' = $email, ' password ' + $password], $remember)} {  //the user is being remembered. .}

If you are logged in as a remembered user, then you can use the Viaremember method to determine whether the user's authentication is by remembering my cookie:

if (Auth::viaremember ()) {  //}

Other authentication methods

Authenticating with a user instance

If you need to record an existing user instance in your app, you can use the login method. The given parameter must be an instance of the implementation of the illuminate\contracts\auth\authenticatable contract. Of course, the APP\USER model has implemented this interface in Laravel:

Auth::login ($user);

Of course, you can also specify a guard instance:

Auth::guard (' admin ')->login ($user);

Direct authentication via User ID

You can use the Loginuseingid method to record a user's information through an ID, which simply receives a primary key for the user who needs authentication:

Auth::loginusingid (1);

Authenticate users only once

The once method only authenticates the user in the current request. No sessions or cookies will be stored. This is useful for building stateless APIs. The once method and attempt have the same visa method:

if (Auth::once ($credentials)) {  //}

HTTP-based authentication

HTTP-based authentication provides a fast user authentication mechanism without having to set up a dedicated login page. In order to start, you should attach auth.basic middleware to your route. Laravel has built-in auth.basic middleware, so you don't need to define it:

Route::get (' profile ', [' middleware ' = ' auth.basic ', function () {  //* * Authenticated Users may enter ...}]);

Once the middleware is attached to the route, you will be prompted for authentication information each time you access the route. By default, the Auth.basic middleware uses an email column as the user name for the user record.

FastCGI Tips

If you use PHP FastCGI, HTTP-based authentication may not work correctly. You can try adding the following in the. htaccess file:

Rewritecond%{http:authorization} ^ (. +) $RewriteRule. *-[E=http_authorization:%{http:authorization}]

Stateless HTTP Basic Authentication

You can also save the user's identity to a cookie without using the session when using HTTP Basic authentication. This is especially 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 is further passed to the application:

     

Next, attach the middleware in 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.

Password reset

Database considerations

Most apps provide a way for users to reset their forgotten passwords. Laravel provides a convenient way to send password hints and provide password resets so you don't have to be forced to implement this mechanism once in every application.

To get started, make sure your app\user model implements the Illuminate\contracts\auth\canresetpassword contract, which has been implemented in the App\user model of Laravel, and uses Illuminate\auth\passwords\canresetpassword trait.

Generate a password reset table by migrating

Next, you must create a table to store tokens for resetting the password. Laravel has provided this kind of table migration and is stored in the Database/migrations directory, so you only need to perform the migration command:

PHP Artisan Migrate

Routing

The laravel comes with a Auth\passwordcontroller controller that contains all the logic required to reset the password. All routes that provide password resets can be generated through the Make:auth Artisan command:

PHP Artisan Make:auth

View

When the Make:auth command is executed, Laravel generates all the views needed to reset the password. These views will be stored in the Resources/views/auth/passwords directory and you can modify them to suit your needs.

After resetting the password

Once you have generated all the routes and views needed to reset the password, you can reset the password by accessing the/password/reset route in the browser. Passwordcontroller already includes the ability to send a linked message to reset the password and to update the password to the database.

When the password is reset, the user is automatically logged in and redirected to/home. You can define the Redirectto property in Passwordcontroller to customize the redirect address:

protected $redirectTo = '/dashboard ';

Note that, by default, the token for password reset is valid for only one hours, and you can modify the Expire option in the config/auth.php configuration file.

Custom

Custom Certified Guard

In the auth.php configuration file, you can configure multiple "guards" to perform authentication actions on a variety of user tables. You can use the $guard property in Passwordcontroller to select the guard:

/** * The authentication guard that should is used. * * @var String */protected $guard = ' admins ';

Custom Password Brokers

In the auth.php configuration file, you can configure a variety of password "brokers" for password reset on a variety of user tables. You can choose by adding $broker properties to the Passwordcontroller:

/** * The password broker that should is used. * * @var String */protected $broker = ' admins ';

Add a custom Guard

You 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 a Illuminate\contracts\auth\guard implementation in the Extend method. In order to customize the guard you need to implement the methods contained 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 ' and ' users '  ];

Add a custom user provider

If you are not using a traditional relational database to store your users, then you need to provide your own user provider to extend the laravel. You can define your own user provider by using the provider method of the Auth mask. You should call this method in the service provider:

       

After you register the provider with the provider method, you need to switch your user provider to the newly registered provider in the config/auth.php configuration file:

' Providers ' = [  ' users ' and ' = '    driver ' = ' Riak ',  ],

Then, you need to use the provider in the Guards option:

' Guards ' + [  ' web ' = [    ' driver ' = ' session ',    ' provider ' and ' users ',  ],],

User provider Contract

The implementation of Illuminate\contracts\auth\userprovider is simply managing how to get a illuminate\contracts\auth\authenticatable implementation from a continuous storage system. such as Mysql,riak, and so on. This two interface implements the Laravel continuous authentication mechanism without having to consider where the user data is stored or what type of storage it is.

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, such as a self-increasing primary key ID in the MySQL database. The matched ID should return an implementation of the authenticatable.

The Retrievebytoken method receives a unique identity to identify the user $identifier and Remember_token stores the $token "Remember Me". As in the previous method, the method should return an authenticatable implementation.

The Updateremembertoken method uses the new $token to update the user's Remember_token field. This new field can be a user login successful and set to remember me and assigned, or it can be the user log out after the assignment of NULL.

The Retrievebycredentials method receives an array credential that passes the credentials to the Auth::attemp method when the user attempts to log on. This method asks for the match of the underlying persistent storage device credential, which is typically used by the WHERE Condition statement to query $credentials [' username '] similar match condition. This method should return an implementation of userinterface. Do not password Authentication or authentication in this method .

The Validatecredentials method should compare the matching of the given user and credentials. For example, this method might compare $credentials [' password '] after $user-getauthpassword () and Hash::make. This method should only do the validation between the user and the voucher and return the Boolean value of the comparison situation.

Certified (authenticatable) contracts

Just now that we have explored all the methods in Userprovider, let's take a look at the authenticatable contract, and you should remember that the provider should be from Retrievebyid and retrievebycredentials method returns the implementation of the contract interface:

         

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 the self-growing primary key value. Getauthpassword should return the hashed password of the user. This interface allows the authentication system to run in any user class without having to control what ORM or other storage abstraction layer you are using. By default, Laravel contains the User class in the app directory, and the class implements the contract. So you can refer to how this class is implemented.

Event

Laravel provides a variety of events in the authentication process. You can attach the listener to these events in 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 ',  ],];
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    Tags Index: