Basic Token Authentication with Laravel 8 (Sanctum) and ReactJs

Suton Tamimy
3 min readSep 28, 2021

--

I just start learning these two Frameworks, so this tutorial will only provide a very basic preparation to integrate these two frameworks as simple as possible using API Token.

Some requirements are: Sanctum for Laravel and Axios for ReactJs.

Laravel Part

There are many tutorial on setting up Laravel with Sanctum. To make this one short I just use Laravel Breeze starter kits to get all user related operations & modules prepared. For this backend I use API URL: http://vel.localhost/api.

Start by installing default Laravel :

composer create-project laravel/laravel my-backend

Then in my-backend directory, make sure you have working database setup in .env file.

Install Breeze by typing these commands :

composer require laravel/breeze — dev
php artisan breeze:install
npm install
npm run dev
php artisan migrate

After this step, you can try registering some users.

Next, create API Controller to handle authentication and Token generation :

php artisan make:controller Api/AuthController --api

In AuthController, use this code to handle login action

<?phpnamespace App\Http\Controllers\Api;use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function login(Request $request)
{
$attr = $request->validate([
'email' => 'required|string|email|',
'password' => 'required|string|min:6'
]);
if (!Auth::attempt($attr)) {
return response()->json([
'message' => 'Invalid login details'
], 401);
}
$token = auth()->user()
->createToken('auth_token')->plainTextToken;
$user = auth()->user();

$respon = [
'status' => 'success',
'msg' => 'Login successfully',
'content' => [
'status_code' => 200,
'access_token' => $token,
'token_type' => 'Bearer',
'user_name' => $user->name,
'user_email' => $user->email,
'user_id' => $user->id,
]
];

return response()->json($respon, 200);
}
}

Then register the action above in file routes/api.php

Route::post('/login', [\App\Http\Controllers\Api\AuthController::class, 'login']);

Now you can test this API using Postman

After this step, you can start register more APIs protected with middleware Sanctum such as this API route :

Route::middleware('auth:sanctum')->apiResource('users', \App\Http\Controllers\Api\UserController::class);

ReactJs Part

Start by installing ReactJs and Axios using these commands :

npx create-react-app react-test
cd react-test
npm install axios
npm start

Your browser will launch with URL http://localhost:3000.

Now, Create file /src/components/Login.js with this content :

import React, { useEffect } from 'react';
import axios from 'axios';
function Login() {
useEffect(() => {
axios.defaults.baseURL = 'http://vel.localhost/api/';
axios.post('/login', {
email: "admin@gmail.com",
password: "password"
})
.then(({ data }) => {
if(data.status==="success"){
console.log(data)
} else {
console.log("error")
}
});
});
return (
<div className="Login">Auto Login</div>
);
}
export default Login;

Above code is for testing. In real world application you need to create Login Form of course.

Then in file /src/App.js, add Login component above :

import logo from './logo.svg';
import './App.css';
import Login from './components/Login';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<Login />
</header>
</div>
);
}
export default App;

Now in browser (Chrome) launch Developer tools (Console) and you’ll see success log like this

After this step, you can start making authenticated API calls using access_token and Bearer token_type given, probably adding this headers needed for API call.

headers: { Authorization: `Bearer ${access_token}` }

Problem

I encountered one problem in ReactJs part using specifically Brave browser. The API call is always rejected when option Trackers & ads blocking is active like picture below.

When I set this option disabled, the API call is working normally. I don’t have this problem in all other browsers such as Chrome, Firefox, Opera, Edge.

Conclusion

That’s it. There are many other authentication methods such as: Cookie based utilizing sanctum/csrf-cookie, Oauth, SSO etc.

Thanks.

--

--