---
description: some authentication code to authenticate users using Laravel Sanctum
---

# Sanctum Authentication

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 <a href="#step-2-create-controller" id="step-2-create-controller"></a>

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

```yang
php artisan make:controller AuthController
```

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

### Create Route <a href="#step-1-create-route" id="step-1-create-route"></a>

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

<pre class="language-dataweave"><code class="lang-dataweave">&#x3C;?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
<strong>use App\Http\Controllers\AuthController;
</strong>/*
|--------------------------------------------------------------------------
| 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!
|
*/

<strong>Route::group(['prefix' => 'auth'], function () {
</strong><strong>    Route::post('login', [AuthController::class, 'login']);
</strong><strong>    Route::post('register', [AuthController::class, 'register']);
</strong><strong>
</strong><strong>    Route::group(['middleware' => 'auth:sanctum'], function() {
</strong><strong>      Route::get('logout', [AuthController::class, 'logout']);
</strong><strong>      Route::get('user', [AuthController::class, 'user']);
</strong><strong>    });
</strong><strong>});
</strong></code></pre>

{% hint style="info" %}
We will create APIs and to test those APIs on [POSTMAN](https://www.postman.com/downloads/).
{% endhint %}

### Register User API <a href="#step-3-register-user-api" id="step-3-register-user-api"></a>

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

<pre class="language-php"><code class="lang-php">&#x3C;?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
<strong>use App\Models\User;
</strong>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']);
        }
    }
</code></pre>

{% hint style="info" %}
Test your register api on **Postman**&#x20;

Select Method:<mark style="color:green;">`POST`</mark>

API: <mark style="color:red;">`http://127.0.0.1:8000/api/auth/register`</mark>
{% endhint %}

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

| Name         | Type | Description          |
| ------------ | ---- | -------------------- |
| `name`       | text | Name of the user     |
| `email`      | text | Email of the user    |
| `password`   | text | Password of the user |
| `c_password` | text | Confirm password     |

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

**Response**

{% tabs %}
{% tab title="201" %}
```json
{
  "mesaage": "Successfully created user!",
  "accessToken": "9|nDyVOuzmExVZP7r0mq97f0rWdECWbRDvgmiKDkD1979a8a9e"
}
```
{% endtab %}
{% endtabs %}

**Capture screenshot of postman for demo purpose:**

<figure><img src="https://3025910797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQ3eW0J6vSeXKIjq75PiA%2Fuploads%2FD1c69OcNaSJFR080TG85%2FScreenshot%202024-04-02%20115618.png?alt=media&#x26;token=de254a61-f339-4136-83d0-f8e42a8e527c" alt=""><figcaption><p>Postman screenshot for register api</p></figcaption></figure>

### Login User API <a href="#step-4-login-user-api" id="step-4-login-user-api"></a>

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

```php
/**
     * 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',
        ]);
    }
```

{% hint style="info" %}
Test your login api on **Postman**&#x20;

Select Method:<mark style="color:green;">`POST`</mark>

API: <mark style="color:red;">`http://127.0.0.1:8000/api/auth/login`</mark>
{% endhint %}

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

<table><thead><tr><th width="345">Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>email</code></td><td>text</td><td>Email of the user</td></tr><tr><td><code>password</code></td><td>text</td><td>Password of the user</td></tr></tbody></table>

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

**Response**

{% tabs %}
{% tab title="200" %}
```json
{
    "accessToken": "9|nDyVOuzmExVZP7r0mq97f0rWdECWbRDvgmiKDkD1979a8a9e",
    "token_type": "Bearer"
}
```
{% endtab %}
{% endtabs %}

**Capture screenshot of postman for demo purpose:**

<figure><img src="https://3025910797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQ3eW0J6vSeXKIjq75PiA%2Fuploads%2FE2TQQt6PH2evrEhkpRid%2FScreenshot%202024-04-29%20170333.png?alt=media&#x26;token=ebeabdf8-7495-435f-9c28-749bf17a61ca" alt=""><figcaption><p>postman screenshot for login api</p></figcaption></figure>

### Get User API <a href="#step-5-get-user-api" id="step-5-get-user-api"></a>

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

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

{% hint style="info" %}
Test your user api on **Postman**&#x20;

Select Method:<mark style="color:green;">`GET`</mark>

API: <mark style="color:red;">`http://127.0.0.1:8000/api/auth/user`</mark>
{% endhint %}

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

<table><thead><tr><th width="345">Name</th><th>Description</th></tr></thead><tbody><tr><td>accept</td><td>application/json</td></tr><tr><td>Authorization</td><td>Bearer &#x3C;Token></td></tr></tbody></table>

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

**Response**

{% tabs %}
{% tab title="200" %}
```json
{
    "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"
}
```
{% endtab %}
{% endtabs %}

**Capture screenshot of postman for demo purpose:**

<figure><img src="https://3025910797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQ3eW0J6vSeXKIjq75PiA%2Fuploads%2FgANmb86H6JI8jAl4PmLP%2FScreenshot%202024-04-02%20121259.png?alt=media&#x26;token=d0ab5289-22c6-4c19-be7f-cfcf736280e0" alt=""><figcaption><p>postman screenshot for login api</p></figcaption></figure>

### Logout User API <a href="#step-6-logout-user-api" id="step-6-logout-user-api"></a>

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

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

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

}
```

{% hint style="info" %}
Test your logout api on **Postman**&#x20;

Select Method:<mark style="color:green;">`GET`</mark>

API: <mark style="color:red;">`http://127.0.0.1:8000/api/auth/logout`</mark>
{% endhint %}

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

<table><thead><tr><th width="345">Name</th><th>Description</th></tr></thead><tbody><tr><td>accept</td><td>application/json</td></tr><tr><td>Authorization</td><td>Bearer &#x3C;Token></td></tr></tbody></table>

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

**Response**

{% tabs %}
{% tab title="200" %}
```json
{
    "message": "Successfully logged out"
}
```
{% endtab %}
{% endtabs %}

**Capture screenshot of postman for demo purpose:**

<figure><img src="https://3025910797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQ3eW0J6vSeXKIjq75PiA%2Fuploads%2FnKH42y6VN8RGYTqpW067%2FScreenshot%202024-04-02%20121841.png?alt=media&#x26;token=e5610419-efb2-44ad-aa78-4836ff32b1b6" alt=""><figcaption><p>postman screenshot for logout api</p></figcaption></figure>
