Loading

Laravel Swagger Authenticate Users Via Bearer Token

Previously, I have made one article on “How to use DarkaOnLine/L5-Swagger in Laravel” but I have not covered how to authenticate users via bearer token so I thought I have to make another article. So in this article, I am going to show you how to authentication users via a bearer token in Laravel Swagger.

Laravel Swagger

For the API authorization, I am using Laravel Passport and I will cover below API in this artcile.

  • REGISTER NEW USER
  • LOGS USER INTO THE SYSTEM
  • LOGS OUT CURRENT LOGGED IN USER SESSION
  • GET LIST OF USERS

As I am using a custom response type for the JSON. I have created macro service so create ResponseMacroServiceProvider class in providers and don’t forgot to register in config providers.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ResponseMacroServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        response()->macro('APIResponse', function ($data, $message = 'Ok', $status = 1, $code = 200) {
            $data = (!empty($data)) ? $data : [];

            return $this->json([
                'status'  => $status,
                'message' => $message,
                'data'    => $data
            ], $code);
        });
    }
}

Let’s create AuthController & UsersController in app\Http\Controllers\API directory. Now let’s jump to the coding part and create all API one by one.

1. REGISTER NEW USER:

API Route

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('register', 'API\AuthController@register');

AuthController Class

<?php

namespace App\Http\Controllers\API;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Modules\Users\Entities\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Response as HttpResponse;

class AuthController extends Controller
{
    /**
     * @OA\Post(
     *      path="/register",
     *      tags={"USER"},
     *      summary="REGISTER NEW USER",
     *      operationId="register",
     *      @OA\Parameter(
     *          name="name",
     *          in="query",
     *          required=true,
     *          @OA\Schema(
     *              type="string"
     *          )
     *      ),
     *      @OA\Parameter(
     *          name="email",
     *          in="query",
     *          required=true,
     *          @OA\Schema(
     *              type="string"
     *          )
     *      ),
     *      @OA\Parameter(
     *          name="password",
     *          in="query",
     *          required=true,
     *          @OA\Schema(
     *              type="string"
     *          )
     *      ),
     *      @OA\Response(
     *          response=200,
     *          description="Success"
     *      )
     * )
     *
     * Register new user.
     *
     * @param Request $request
     * @return void
    */
    public function register(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name'     => 'required',
                'email'    => 'required|email|unique:users',
                'password' => 'required'
            ]);

            if ($validator->fails()) {
                return response()->APIResponse('', $validator->errors()->first(), 0, 200);
            } else {
                $userObj = new User([
                    'name'     => ucwords($request->name),
                    'email'    => $request->email,
                    'password' => Hash::make($request->email)
                ]);
                if ($userObj->save()) {
                    $data = [
                        'user_id'      => $userObj->id,
                        'name'         => $userObj->name,
                        'email'        => $userObj->email,
                        'token_type'   => 'Bearer',
                        'access_token' => $userObj->createToken('Personal Access Token')->accessToken
                    ];

                    return response()->APIResponse($data, 'Your account has been created successfully.', 1, 200);
                } else {
                    return response()->APIResponse('Oops! Something went wrong.', $validator->errors()->first(), 0, 200);
                }
            }
        } catch (\Exception $e) {
            return response()->APIResponse('', $e->getMessage(), 0, 500);
        }
    }
}

Swagger Preview

Laravel Swagger

2. LOGS USER INTO THE SYSTEM

API Route

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('login', 'API\AuthController@login');

AuthController Class

<?php

namespace Modules\Users\Http\Controllers\API;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Modules\Users\Entities\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Response as HttpResponse;

class AuthController extends Controller
{
    /**
     * @OA\Post(
     *      path="/login",
     *      tags={"USER"},
     *      summary="LOGS USER INTO THE SYSTEM",
     *      operationId="login",
     *      @OA\Parameter(
     *          name="email",
     *          in="query",
     *          required=true,
     *          @OA\Schema(
     *              type="string"
     *          )
     *      ),
     *      @OA\Parameter(
     *          name="password",
     *          in="query",
     *          required=true,
     *          @OA\Schema(
     *              type="string"
     *          )
     *      ),
     *      @OA\Response(
     *          response=200,
     *          description="Success"
     *      )
     * )
     *
     * Logs user into the system.
     *
     * @param Request $request
     * @return void
    */
    public function login(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'email'    => 'required|email',
                'password' => 'required'
            ]);

            if ($validator->fails()) {
                return response()->APIResponse('', $validator->errors()->first(), 0, 200);
            } else {
                if (!Auth::attempt(['email' => $request->email, 'password' => $request->password, 'status' => 'active'])) {
                    return response()->APIResponse('', 'The Email or Password you entered is incorrect or the account has been disabled.', 0, 200);
                } else {
                    $user = $request->user();
                    $tokenResult = $user->createToken('Personal Access Token');

                    $data = [
                        'user_id'      => Auth::user()->id,
                        'name'         => Auth::user()->name,
                        'email'        => Auth::user()->email,
                        'token_type'   => 'Bearer',
                        'access_token' => $tokenResult->accessToken
                    ];

                    return response()->APIResponse($data, 'You have been authenticated successfully.', 1, 200);
                }
            }
        } catch (\Exception $e) {
            return response()->APIResponse('', $e->getMessage(), 0, 500);
        }
    }
}

Swagger Preview

Laravel Swagger

3. LOGS OUT CURRENT LOGGED IN USER SESSION:

API Route

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::group([
    'middleware' => 'auth:api'
], function () {
    Route::get('logout', 'API\AuthController@logout');
});

AuthController Class

<?php

namespace Modules\Users\Http\Controllers\API;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Modules\Users\Entities\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Response as HttpResponse;

class AuthController extends Controller
{
    /**
     * @OA\Get(
     *     path="/logout",
     *     tags={"USER"},
     *     summary="LOGS OUT CURRENT LOGGED IN USER SESSION",
     *     operationId="logout",
     *     @OA\Response(
     *         response=200,
     *         description="Success"
     *     ),
     *     security={
     *         {"bearer": {}}
     *     }
     * )
     *
     * Logs out current logged in user session.
     *
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        try {
            $request->user()->token()->revoke();

            return response()->APIResponse('', 'You have been logged out successfully.', 1, 200);
        } catch (\Exception $e) {
            return response()->APIResponse('', $e->getMessage(), 0, 500);
        }
    }
}

Swagger Preview

Laravel Swagger

4. GET LIST OF USERS:

API Route

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::group([
    'middleware' => 'auth:api'
], function () {
    Route::get('getUsers', 'API\UsersController@getUsers');
});

UsersController Class

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Modules\Users\Entities\User;
use App\Http\Controllers\Controller;

class UsersController extends Controller
{
    /**
     * @OA\Get(
     *     path="/getUsers",
     *     tags={"USER"},
     *     summary="GET LIST OF USERS",
     *     operationId="getUsers",
     *     @OA\Response(
     *         response=200,
     *         description="Success"
     *     ),
     *     security={
     *         {"bearer": {}}
     *     }
     * )
     *
     * Get list of users.
     *
     * @param Request $request
     * @return void
     */
    public function getUsers(Request $request)
    {
        try {
            // Get all users
            $data = User::where('status', 'active')->get();

            return response()->APIResponse($data, 'List of users.', 1, 200);
        } catch (\Exception $e) {
            return response()->APIResponse('', $e->getMessage(), 0, 500);
        }
    }
}

Swagger Preview

api integration

api integration

Keep visiting for new stuff and give your feedback.

Happy Coding 😉

%d bloggers like this: