{"flag":true,"single":true,"pageTitle":"LARAVEL API using Sanctum","post":{"id":255,"user_id":"1","slug":"laravel-api-using-sanctum-t4c5","title":"LARAVEL API using Sanctum","body":"<p>Packages used to create api are<strong> 1. sanctum <\/strong>and <strong>2. Passport <\/strong>we will use sanctum in this guide.<\/p>\r\n<p><strong>Laravel Sanctum provides a featherweight authentication system. IT solve two separate problems.<\/strong><\/p>\r\n<ol>\r\n<li><strong>API TOKENS<br><\/strong>First, issue API tokens to your users without the complication of OAuth. It store user API tokens in a single <strong>database table<\/strong> and authenticating incoming <strong>HTTP requests via the Authorization header <\/strong>which should contain a valid API token. So user need to generate a token to use API<\/li>\r\n<li><strong>SPA Authentication::&nbsp;<br><\/strong>https:\/\/laravel.com\/docs\/11.x\/sanctum#spa-authentication<strong><br><\/strong><\/li>\r\n<\/ol>\r\n<p style=\"font-weight: bold;\">How sanctum works:<br>If login cred are correct it save a token in database and return to user, user need to send that token with every request&nbsp;<\/p>\r\n<p><strong>Installation:<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>php artisan install:api<\/code><\/pre>\r\n<p>OR<\/p>\r\n<pre class=\"language-markup\"><code>composer require laravel\/sanctum\r\nphp artisan vendor:publish --provider=\"Laravel\\Sanctum\\SanctumServiceProvider\"<\/code><\/pre>\r\n<p>after installation run below command to add new database table <strong>personal_access_tokens<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>php artisan migrate<\/code><\/pre>\r\n<p><strong>Set Up Sanctum Middleware:<\/strong><\/p>\r\n<p>&nbsp;For APIs, you should add Sanctum's middleware to your api middleware group in <strong>app\/Http\/Kernel.php:<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>'api' =&gt; [\r\n    \\Laravel\\Sanctum\\Http\\Middleware\\EnsureFrontendRequestsAreStateful::class,\r\n    'throttle:api',\r\n    \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\r\n],<\/code><\/pre>\r\n<p><strong>Add Sanctum's Middleware to API Authentication:<\/strong> If you are using Sanctum to protect API routes, update the api guard inside your <strong>config\/auth.php<\/strong> file:<\/p>\r\n<pre class=\"language-markup\"><code>'guards' =&gt; [\r\n    'api' =&gt; [\r\n        'driver' =&gt; 'sanctum',\r\n        'provider' =&gt; 'users',\r\n        'hash' =&gt; false,\r\n    ],\r\n],\r\n<\/code><\/pre>\r\n<p>&nbsp;Now, you can use Sanctum to issue tokens or authenticate API requests using tokens.<\/p>\r\n<p>&nbsp;<\/p>\r\n<p>To issuing tokens for users, your User model should use the <strong>Laravel\\Sanctum\\HasApiTokens<\/strong> trait:<\/p>\r\n<pre class=\"language-markup\"><code>\/\/Models\/User.php\r\nuse Laravel\\Sanctum\\HasApiTokens;\r\nclass User extends Authenticatable\r\n{\r\n    use HasApiTokens, HasFactory, Notifiable;\r\n}<\/code><\/pre>\r\n<p>To issue a token, you may use the <strong>createToken <\/strong>method. API tokens (SHA-256) hashing before being stored in your database, but you may access the plain-text value of the token using the <strong>plainTextToken <\/strong>property of the NewAccessToken instance. You should display this value to the user immediately after the token has been created:<\/p>\r\n<pre class=\"language-markup\"><code>use Illuminate\\Http\\Request;\r\nRoute::post('\/tokens\/create', function (Request $request) {\r\n    $token = $request-&gt;user()-&gt;createToken($request-&gt;token_name);\r\n \r\n    return ['token' =&gt; $token-&gt;plainTextToken];\r\n});\r\n\r\n\/\/if user is authenticated show him token<\/code><\/pre>\r\n<p><strong>ACCESS TOKENS:<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>foreach ($user-&gt;tokens as $token) {\r\n    \/\/ ...\r\n}\r\n\/\/ OR  FIND A SINGLE USER THEN\r\n$user-&gt;tokens()<\/code><\/pre>\r\n<p><strong>Token Abilities<\/strong><\/p>\r\n<p>xd learn it&nbsp;<\/p>\r\n<p><strong>Protecting Routes<\/strong><\/p>\r\n<p>To protect routes so that all incoming requests must be authenticated, you should attach the&nbsp;<code>sanctum<\/code> authentication guard&nbsp;<\/p>\r\n<pre class=\"language-markup\"><code>use Illuminate\\Http\\Request;\r\nRoute::get('\/user', function (Request $request) {\r\n    return $request-&gt;user();\r\n})-&gt;middleware('auth:sanctum');<\/code><\/pre>\r\n<p><strong>Revoking Tokens<\/strong><\/p>\r\n<p>You may \"revoke\" tokens by deleting them from your database using the tokens relationship<\/p>\r\n<pre class=\"language-markup\"><code>\/\/ Revoke all tokens...\r\n$user-&gt;tokens()-&gt;delete();\r\n \r\n\/\/ Revoke the token that was used to authenticate the current request...\r\n$request-&gt;user()-&gt;currentAccessToken()-&gt;delete();\r\n \r\n\/\/ Revoke a specific token...\r\n$user-&gt;tokens()-&gt;where('id', $tokenId)-&gt;delete();<\/code><\/pre>\r\n<p><strong>Token expiration add:<\/strong><\/p>\r\n<p>If you would like to specify the expiration time of each token independently, you may do so by providing the expiration time as the third argument to the createToken method:<\/p>\r\n<pre class=\"language-markup\"><code>return $user-&gt;createToken(\r\n    'token-name', ['*'], now()-&gt;addWeek()\r\n)-&gt;plainTextToken;<\/code><\/pre>\r\n<p>&nbsp;<\/p>\r\n<p><strong>A MINI EXAMPLE:<\/strong><\/p>\r\n<p><strong>Make controller<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>php artisan make:controller AuthController<\/code><\/pre>\r\n<pre class=\"language-markup\"><code>&lt;?php\r\nnamespace App\\Http\\Controllers;\r\nuse Illuminate\\Http\\Request;\r\nuse Illuminate\\Support\\Facades\\Auth;\r\nuse App\\Models\\User;\r\n\r\nclass AuthController extends Controller\r\n{\r\n    \/\/ Method for user login and issuing a token\r\n    public function login(Request $request)\r\n    {\r\n        $credentials = $request-&gt;validate([\r\n            'email' =&gt; 'required|email',\r\n            'password' =&gt; 'required'\r\n        ]);\r\n\r\n        if (Auth::attempt($credentials)) {\r\n            $user = Auth::user();\r\n            $token = $user-&gt;createToken('API Token ETC')-&gt;plainTextToken;\r\n\r\n            return response()-&gt;json([\r\n                'message' =&gt; 'Login successful',\r\n                'token' =&gt; $token\r\n            ], 200);\r\n        }\r\n\r\n        return response()-&gt;json([\r\n            'message' =&gt; 'Invalid credentials'\r\n        ], 401);\r\n    }\r\n    \/\/ Method to log out the user and revoke the token\r\n    public function logout(Request $request)\r\n    {\r\n        \/\/ Revoke all tokens...\r\n        $request-&gt;user()-&gt;tokens()-&gt;delete();\r\n        return response()-&gt;json([\r\n            'message' =&gt; 'Logged out successfully'\r\n        ], 200);\r\n    }\r\n    \/\/ Method to get the authenticated user details\r\n    public function user(Request $request)\r\n    {\r\n        return response()-&gt;json($request-&gt;user());\r\n    }\r\n}<\/code><\/pre>\r\n<p><strong>Routes\\api.php<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>use App\\Http\\Controllers\\AuthController;\r\n\/\/ Public route for login\r\nRoute::post('\/login', [AuthController::class, 'login']);\r\n\r\n\/\/ Protected routes\r\nRoute::middleware('auth:sanctum')-&gt;group(function () {\r\n    Route::post('\/logout', [AuthController::class, 'logout']);\r\n    Route::get('\/user', [AuthController::class, 'user']);\r\n});\r\n<\/code><\/pre>\r\n<p>Send a POST request to <strong>\/api\/login<\/strong> with email and password. If successful, it will return a token.<\/p>\r\n<p>&nbsp;<\/p>","category_id":"2","is_private":"0","created_at":"2024-09-04T12:38:21.000000Z","updated_at":"2024-09-04T22:31:33.000000Z","category":{"id":2,"user_id":"1","name":"Laravel Core","slug":"laravel-nhyt","parent_id":"1","created_at":"2023-03-14T03:58:27.000000Z","updated_at":"2023-03-20T11:30:50.000000Z"},"user":{"id":1,"name":"R GONDAL","email":"rizikmw@gmail.com","email_verified_at":null,"two_factor_confirmed_at":null,"current_team_id":"1","profile_photo_path":null,"created_at":"2023-03-12T10:49:33.000000Z","updated_at":"2025-01-10T12:59:00.000000Z","profile_photo_url":"https:\/\/ui-avatars.com\/api\/?name=R+G&color=7F9CF5&background=EBF4FF"}},"pageDesc":"Packages used to create api are 1. sanctum and 2. Passport we will use sanctum in this guide. Laravel Sanctum provides a featherweight authe - LARAVEL API using Sanctum (Updated: September 4, 2024) - Read more about LARAVEL API using Sanctum at my programming site [SITE]","categories":[]}