AdnanTech Laravel Get auth user without sanctum middleware – Laravel

Get auth user without sanctum middleware – Laravel

In order to get an authentication user without using sanctum middleware in Laravel, you just need to pass the string “sanctum” in auth() method.

Auth sanctum without middleware

Following route goes in the “routes/api.php” file:

# routes/api.php

Route::post("/auth-without-sanctum", function () {
    return auth("sanctum")->user();
});

Auth sanctum with middleware

If you do not want to use the “sanctum” string in auth() method, then you need to wrap your route inside sanctum middleware. Like this:

Route::group([
    "middleware" => ["auth:sanctum"]
], function () {

    Route::post("/auth-without-sanctum", function () {
        return auth()->user();
    });
    
});

Generate API Token

In order to check if the above code is working fine, we need to call an AJAX with authorization token. To create an authorization token (just for testing), we will use the following code:

# app/Http/Controllers/UserController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;
use App\Models\User;

class UserController extends Controller
{
    public function generate_token()
    {
        $user = DB::table("users")
            ->where("email", "=", "adnan@gmail.com")
            ->first();

        if ($user == null)
        {
            $id = DB::table("users")
                ->insertGetId([
                    "name" => "Adnan",
                    "email" => "adnan@gmail.com",
                    "password" => password_hash("adnan", PASSWORD_DEFAULT),
                    "created_at" => now()->utc(),
                    "updated_at" => now()->utc()
                ]);
        }
        else
        {
            $id = $user->id;
        }

        $user = User::where("id", "=", $id)->first();

        $token = $user->createToken("adnan-tech.com")->plainTextToken;
        dd($token);
    }
}

createToken(secret_string) method accepts a secret string that will be used to generate plain text tokens. You can write any string you want. Copy the value of $token variable and use it in AJAX request later in this tutorial.

Note: If you face an error while generating a token, run the following command in your terminal:

php artisan install:api

It will ask you to add Laravel\Sanctum\HasApiTokens trait in your User model. You can add it in the following way:

# app/Models/User.php

...
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens;
    
    ...
}

Learn more about Laravel sanctum from their official documentation.

AJAX with authorization header token

We are calling a simple AJAX request to this API route and passing the token value after “Bearer ” (notice the space).

var ajax = new XMLHttpRequest()
ajax.open("POST", "api/auth-without-sanctum", true)
ajax.setRequestHeader("Accept", "application/json")
ajax.setRequestHeader("Authorization", "Bearer 1|EovaNhClZ1DBrwEMRasAgpfZc7AqNF5yNaBGP76U1be5a11f")

ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText)
    }
}

ajax.send()

Open your browser inspect element and goto “Network” tab, you will see the user object in “Preview”.

Chrome inspect element network - Laravel get authenticated user without using sanctum middleware
Chrome inspect element network

Now try commenting out the line that sends authorization header in AJAX request. You will receive an empty or null response (make sure the API route is not wrapped in auth:sanctum middleware).

Error: Route [login] not defined

If you get an error “Route [login] not defined”.

Route [login] not defined - Laravel
Route [login] not defined – Laravel

Then it can also be fixed by adding the following 2 headers with your AJAX request.

ajax.setRequestHeader("Accept", "application/json")
ajax.setRequestHeader("Authorization", "Bearer 1|EovaNhClZ1DBrwEMRasAgpfZc7AqNF5yNaBGP76U1be5a11f")

And then set the name “login” to your login route.

// web.php

Route::get("/login", function () {
  return view("login");
})->name("login");

More

Learn how to fix 403 forbidden error on Laravel storage

This is how you can get an authenticated (auth() method) user in Laravel without using sanctum middleware.

Related Post