Sanctum Authentication

some authentication code to authenticate users using Laravel Sanctum

This guide shows how to create an API with Laravel Sanctum. You will need to adjust the final output to fit our model. You can view the expected response from different perspectives using the following tools:

Create Controller

Create new controller in Http/Controllers/AuthController.php by the following command:

php artisan make:controller AuthController

then, add routes for api in api.php file and include AuthController

Create Route

Open api.php from routes folder and replace the code of route with the following:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
/*
|--------------------------------------------------------------------------
| 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(['prefix' => 'auth'], function () {
    Route::post('login', [AuthController::class, 'login']);
    Route::post('register', [AuthController::class, 'register']);

    Route::group(['middleware' => 'auth:sanctum'], function() {
      Route::get('logout', [AuthController::class, 'logout']);
      Route::get('user', [AuthController::class, 'user']);
    });
});

We will create APIs and to test those APIs on POSTMAN.

Register User API

Open Http/Controllers/AuthController.php and replace below code:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Validator;

class AuthController extends Controller
{
    /**
    * Create user
    *
    * @param  [string] name
    * @param  [string] email
    * @param  [string] password
    * @param  [string] password_confirmation
    * @return [string] message
    */
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'email'=>'required|string|unique:users',
            'password'=>'required|string',
            'c_password' => 'required|same:password'
        ]);

        $user = new User([
            'name'  => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);

        if($user->save()){
            $tokenResult = $user->createToken('Personal Access Token');
            $token = $tokenResult->plainTextToken;

            return response()->json([
            'message' => 'Successfully created user!',
            'accessToken'=> $token,
            ],201);
        }
        else{
            return response()->json(['error'=>'Provide proper details']);
        }
    }

Test your register api on Postman

Select Method:POST

API: http://127.0.0.1:8000/api/auth/register

Body (Add body data on your postman like below table)

After this click on send button and get response like below.

Response

{
  "mesaage": "Successfully created user!",
  "accessToken": "9|nDyVOuzmExVZP7r0mq97f0rWdECWbRDvgmiKDkD1979a8a9e"
}

Capture screenshot of postman for demo purpose:

Login User API

In the same file Http/Controllers/AuthController.php, add below code before register method:

/**
     * Login user and create token
    *
    * @param  [string] email
    * @param  [string] password
    * @param  [boolean] remember_me
    */

    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->plainTextToken;

        return response()->json([
            'accessToken' =>$token,
            'token_type' => 'Bearer',
        ]);
    }

Test your login api on Postman

Select Method:POST

API: http://127.0.0.1:8000/api/auth/login

Body (Add body data on your postman like below table)

After this click on send button and get response like below

Response

{
    "accessToken": "9|nDyVOuzmExVZP7r0mq97f0rWdECWbRDvgmiKDkD1979a8a9e",
    "token_type": "Bearer"
}

Capture screenshot of postman for demo purpose:

Get User API

In the same file Http/Controllers/AuthController.php, add below code after Login method:

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

Test your user api on Postman

Select Method:GET

API: http://127.0.0.1:8000/api/auth/user

Headers (Add Headers data on your postman like below table)

After this click on send button and get response like below

Response

{
    "id": "1",
    "name": "admin",
    "email": "admin@test.com",
    "email_verified_at": null,
    "created_at": "2024-4-02T06:21:13.000000Z",
    "updated_at": "2024-4-02T06:21:13.000000Z"
}

Capture screenshot of postman for demo purpose:

Logout User API

In the same file Http/Controllers/AuthController.php, add below code after User method:

/**
 * Logout user (Revoke the token)
*
* @return [string] message
*/
public function logout(Request $request)
{
    $request->user()->tokens()->delete();

    return response()->json([
    'message' => 'Successfully logged out'
    ]);

}

Test your logout api on Postman

Select Method:GET

API: http://127.0.0.1:8000/api/auth/logout

Headers (Add Headers data on your postman like below table)

After this click on send button and get response like below

Response

{
    "message": "Successfully logged out"
}

Capture screenshot of postman for demo purpose:

Last updated