Best way to authenticate and identify individual screens in a Laravel API using Passport and JWT?
To authenticate and identify individual screens in a Laravel API using Passport and JWT, you can follow these steps:
-
Set up Laravel Passport: First, you need to set up Laravel Passport as your authentication system. Laravel Passport is a full OAuth2 server implementation for Laravel. You can follow the official Laravel Passport documentation to set it up.
-
Create API routes: Create routes for your API endpoints in
routes/api.php
. Make sure to protect these routes with theauth:api
middleware. -
Create a JWT middleware: Create a middleware to handle JWT authentication. This middleware will decode the JWT token and extract the user and screen information from it. Here's an example of how to create a JWT middleware:
namespace App\Http\Middleware;
use Closure;
use Firebase\JWT\JWT;
class JwtAuthenticate
{
protected $key = 'your_secret_key';
public function handle($request, Closure $next)
{
$token = $request->header('Authorization');
if (!$token) {
return response()->json(['error' => 'Token not provided'], 401);
}
try {
$decoded = JWT::decode($token, $this->key, array('HS256'));
$request->merge($decoded);
// Add user and screen information to the request object
$request->user = Auth::guard('api')->authenticate($decoded->user);
$request->screen = $decoded->screen;
return $next($request);
} catch (\Exception $e) {
return response()->json(['error' => 'Invalid token'], 401);
}
}
}
- Create a JWT factory: Create a JWT factory to generate JWT tokens with user and screen information. Here's an example of how to create a JWT factory:
namespace App\Http\Middleware;
use Firebase\JWT\JWT;
use Illuminate\Contracts\Auth\Authenticatable;
class JwtFactory
{
protected $key = 'your_secret_key';
public function createToke($user, $screen)
{
$data = [
'iat' => time(),
'exp' => time() + 60 * 60 * 24 * 30, // token expiration in 30 days
'user' => $user,
'screen' => $screen,
];
return JWT::encode($data, $this->key);
}
}
- Create a JWT controller: Create a controller to handle JWT token generation and validation. Here's an example of how to create a JWT controller:
namespace App\Http\Controllers;
use App\Http\Middleware\JwtAuthenticate;
use App\Http\Middleware\JwtFactory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class JwtController extends Controller
{
protected $jwtFactory;
public function __construct(JwtFactory $jwtFactory)
{
$this->jwtFactory = $jwtFactory;
}
public function login(Request $request)
{
$credentials = $request->only(['email', 'password']);
if (!Auth::guard('api')->attempt($credentials)) {
return response()->json(['error' => 'Invalid credentials'], 401);
}
$user = Auth::guard('api')->user();
$screen = $request->screen;
return response()->json([
'token' => $this->jwtFactory->createToken($user, $screen),
]);
}
public function me()
{
return response()->json(Auth::guard('api')->user());
}
}
- Protect your API endpoints: Protect your API endpoints with the JWT middleware. Here's an example of how to protect an API endpoint:
Route::get('/api/protected', 'YourController@protectedEndpoint')
->middleware('jwt.authenticate');
- Make API requests:
To make API requests, include the JWT token in the
Authorization
header of the request. Here's an example of how to make an API request:
$token = $this->jwtFactory->createToken($user, $screen);
$headers = [
'Authorization' => 'Bearer ' . $token,
];
$response = $client->get('/api/protected', [
'headers' => $headers,
]);
With these steps, you can authenticate and identify individual screens in a Laravel API using Passport and JWT.