This post is from the professional Laravel developer community, original link: learnku.com/laravel/t/2…

We’ll learn to use Laravel’s Passport API OAuth to create an authentication system.

Step 1: Install Laravel

We need to create the latest Laravel application with the following command, so open the terminal to execute:

laravel new auth
Copy the code

Step 2: Install the Laravel Passport package

The Laravel Passport can implement a full OAuth2 server for your application in minutes.

composer require laravel/passport
Copy the code

Step 3. Run the database migration

Migration of Passport creates tables that your application uses to store client and Access tokens.

php artisan migrate
Copy the code

Step 4. Generate the secret key

This command creates the secret key used to generate secure Access tokens. In addition, it also creates personal Access and password grant to generate Access tokens:

php artisan passport:install
Copy the code

Once done, add the Laravel\Passport\HasApiTokens trait to your App\User model. This trait adds a set of helper functions to the model to verify the user’s secret key and scope:

Step 5. Passport configuration

<? php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use Notifiable, HasApiTokens; }Copy the code

Next, you should call the Passport:: Routes method in the Boot method of the AuthServiceProvider. This method registers the necessary routes to issue and revoke access tokens, client and personal tokens:

<? php namespace App\Providers; use Laravel\Passport\Passport; use Illuminate\Support\Facades\Gate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * The policy mappingsfor the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model'= >'App\Policies\ModelPolicy',]; /** * Register any authentication / authorization services. * * @return void
     */
    public function boot()
    {
        $this->registerPolicies(); Passport::routes(); }}Copy the code

Finally, in the config/auth.php configuration file, you should set the API permission guard driver option to Passport. Tells your application to use Passport’s TokenGuard when an API request that requires permission authentication comes in.

'guards'= > ['web'= > ['driver'= >'session'.'provider'= >'users',].'api'= > ['driver'= >'passport'.'provider'= >'users',]],Copy the code

Step 6 add an API route

Laravel provides the routes/api.php file to write our Web routes, so just add a new route to this file.

<? php use Illuminate\Http\Request; Route::group(['prefix'= >'auth'].function () {
    Route::post('login'.'AuthController@login');
    Route::post('signup'.'AuthController@signup');

    Route::group([
      'middleware'= >'auth:api'].function() {
        Route::get('logout'.'AuthController@logout');
        Route::get('user'.'AuthController@user');
    });
});
Copy the code

Step 7: Create a controller

As a final step we must create new controller and API methods. So let’s create the AuthController and put the code in:

<? php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Carbon\Carbon; use App\User; class AuthController extends Controller { /** * Create user * * @param [string] name * @param [string] email * @param [string] password * @param [string] password_confirmation * @return [string] message
     */
    public function signup(Request $request)
    {
        $request->validate([
            'name'= >'required|string'.'email'= >'required|string|email|unique:users'.'password'= >'required|string|confirmed'
        ]);
        
        $user = new User([
            'name'= >$request->name,
            'email'= >$request->email,
            'password' => bcrypt($request->password)
        ]);
        
        $user->save();
        
        return response()->json([
            'message'= >'Successfully created user! '
        ], 201);
    }

    /**
     * Login user and create token
     *
     * @param  [string] email
     * @param  [string] password
     * @param  [boolean] remember_me
     * @return [string] access_token
     * @return [string] token_type
     * @return [string] expires_at
     */
    public function login(Request $request)
    {
        $request->validate([
            'email'= >'required|string|email'.'password'= >'required|string'.'remember_me'= >'boolean'
        ]);
        
        $credentials = request(['email'.'password']);
        
        if(! Auth::attempt($credentials))
            return response()->json([
                'message'= >'Unauthorized'
            ], 401);
            
        $user = $request->user();
        
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        
        $token->save();
        
        return response()->json([
            'access_token'= >$tokenResult->accessToken,
            'token_type'= >'Bearer'.'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }

    /**
     * Logout user (Revoke the token)
     *
     * @return [string] message
     */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        
        return response()->json([
            'message'= >'Successfully logged out'
        ]);
    }

    /**
     * Get the authenticated User
     *
     * @return [json] user object
     */
    public function user(Request $request)
    {
        return response()->json($request->user()); }}Copy the code

Now that we are ready to run our example, run the following command for a quick run:

php artisan serve
Copy the code

test

Now we can use REST client tools, such as Postman, to simplify testing. I ran the test and you can see the screenshot below.

You need to set the following two headers for this API:

Content-Type: application/json
X-Requested-With: XMLHttpRequest
Copy the code

registered

The login

logout

The user


Thanks for reading!

resources

  • GitHub
  • Postman collections

reference

  • Laravel Passport
  • Create REST API in Laravel with authentication using Passport The author Urjit Rajgor