Secure User Authentication in Laravel & Vue.js Using JWT

blog-banner

JWT Authentication with Laravel and Vue.js

JSON Web Tokens (JWT) provide a secure way to handle authentication in modern web development. By using Laravel JWT Authentication (a powerful PHP backend framework) together with Vue.js JWT Authentication (a progressive JavaScript frontend framework), developers can build a robust JWT-based authentication system. If you’re looking to implement secure and scalable solutions, you can hire a Laravel developer to help you integrate JWT authentication seamlessly with Vue.js for your next project.

What is JWT?

JSON Web Token is a secure and authentic way to transmit information between systems in the form of JSON objects. It is digitally signed to ensure data integrity and security. JWT is specifically used in API authentication in place of a session-based system.

A JWT consists of three components:

  1. Header – The token type (JWT) and signature algorithm are included within it.
  2. Payload – User-related information, such as user ID, email, and roles, is held within it.
  3. Signature – A digital signature is created that verifies the token has not been modified.

How JWT Works

  1. User login: Client (Vue.JS) sends credentials to the server.
  2. Server verification: If valid, the server produces a JWT and sends it back.
  3. Client storage: client (vue.JS) stores tokens (usually in local storage or cookies).
  4. Later request: Tokens are sent to the authority header for protected routes.
  5. Server Verification: The server decoded JWT to certify the user.

Why Use JWT for Authentication?

  • Stateless certification - There is no need to store user sessions on the server.
  • Scalability - perfect for microsarvis and API -operated applications.
  • Security - Encryption and signature verification to prevent molestation.
  • Flexible Uses - Works in many platforms including web and mobile apps.

How Laravel & Vue.js Work Together for JWT Authentication

Laravel as the Backend API

The larval acts as a backend, handling user authentication with Laravel API Authentication, issuing JWT tokens, and managing API access. When a user log in, the largest values the credentials and produces a JWT token, which is sent to the front-end (vue.JS).

Vue.js as the Frontend

Vue.JS is a user interface control module of the client-side application. It keeps JWT tokens in the local storage or cookies and attaches them to each API request for authentication purposes. The Vue router guards the paths, allowing authorized users access to restricted pages only.

JWT vs Sanctum

Feature 

JWT 

Sanctum 

Stateless 

Yes (does not require DB queries) 

No (stores tokens in DB) 

Storage 

Local storage, cookies, or headers 

HTTP-only cookies or DB 

Revocable Tokens 

No (unless using a blacklist) 

Yes (can be deleted from DB) 

Best For 

Multi-client API authentication 

First-party SPA authentication 

Security 

Requires manual handling for security 

More secure with cookie-based auth 

Challenges and Considerations

  • Token Expiry: Handling token refresh for better user experience.
  • Security Risks: Protecting against token theft and misuse.
  • Role-Based Access: Managing permissions effectively.
  • Logout Handling: Invalidating tokens after user logout.

Setting Up Laravel for JWT Authentication

1. Install Laravel

 composer create-project laravel/laravel jwt-auth-app cd jwt-auth-app 

2. Install JWT Package

 composer require tymon/jwt-auth 

3. Publish JWT Config and Generate Secret Key

 php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" php artisan jwt:secret 

This adds a key to your .env file:

 JWT_SECRET=your_random_key_here 

4. Configure Auth Guard Update config/auth.php:

 'defaults' => [ 'guard' => 'api', 'passwords' => 'users', ],

'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],

5. Create User Model and Migration

 php artisan make:model User -m 

Update the migration file:

 Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->timestamps(); }); 

Run migration:

 php artisan migrate 

6. Create AuthController

 php artisan make:controller AuthController 

Inside app/Http/Controllers/AuthController.php:

 validate([
'name' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);

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

    $token = auth()->login($user);

    return response()->json([
        'access_token' => $token,
        'token_type' => 'bearer',
        'expires_in' => auth()->factory()->getTTL() * 60,
    ]);
}

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (!$token = auth()->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    return $this->respondWithToken($token);
}

protected function respondWithToken($token)
{
    return response()->json([
        'access_token' => $token,
        'token_type' => 'bearer',
        'expires_in' => auth()->factory()->getTTL() * 60,
    ]);
}

public function me()
{
    return response()->json(auth()->user());
}

public function logout()
{
    auth()->logout();
    return response()->json(['message' => 'Successfully logged out']);
}


}

7. Add API Routes (routes/api.php)

 use App\Http\Controllers\AuthController;

Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);

Route::middleware('auth:api')->group(function () {
Route::post('logout', [AuthController::class, 'logout']);
Route::get('me', [AuthController::class, 'me']);
});

8. Install Vue.js & Axios

 npm install vue@next vue-router axios npm install -D @vitejs/plugin-vue 

9. Create Vue Components (Login.vue)

Login

10. Register.vue

Register

11. Configure Axios Interceptors (main.js)

 import axios from 'axios';

axios.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = Bearer ${token};
}
return config;
});

12. Protect Routes with Vue Router

 import { createRouter, createWebHistory } from 'vue-router'; import Login from './components/Login.vue'; import Register from './components/Register.vue'; import Dashboard from './components/Dashboard.vue';

const routes = [
{ path: '/login', component: Login },
{ path: '/register', component: Register },
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true },
},
];

const router = createRouter({
history: createWebHistory(),
routes,
});

router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !localStorage.getItem('token')) {
next('/login');
} else {
next();
}
});

export default router;

Conclusion: Building Secure Authentication with Laravel and Vue.js

Using Vue.js JWT Authentication with Laravel JWT Authentication is a great way to enhance security, scalability and also make the application more upto-date. So, having Laravel API Authentication in the backend and Vue.js Authentication with Laravel in the frontend, developers will be able to engineer the systems of user authentication which are not only seamless but also efficient. The duo of Vue.js and Laravel JWT is a good tool to speed up your Laravel development, ensure security, and build robust applications for the web today.

Contact us

For Your Business Requirements

Text to Identify Refresh CAPTCHA