To use Laravel as a backend API for a native app, you can use JWT (JSON Web Tokens) for authentication. Here are the steps you can follow:
- Install the tymon/jwt-auth package in your Laravel project using Composer:
composer require tymon/jwt-auth
- Publish the JWT configuration file:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
- Generate a secret key for JWT:
php artisan jwt:secret
- Create an API route in Laravel that returns a JWT token when the user logs in:
Route::post('login', function () {
$credentials = request(['email', 'password']);
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return response()->json(['token' => $token]);
});
-
In your native app, send a POST request to the login API route with the user's email and password. The API will return a JWT token that you can use to authenticate subsequent requests.
-
Include the JWT token in the Authorization header of your API requests from the native app:
Authorization: Bearer <JWT token>
- In Laravel, use the
jwt.authmiddleware to protect your API routes:
Route::middleware('jwt.auth')->get('user', function () {
return auth()->user();
});
This route will return the authenticated user's information if the JWT token is valid.
Note: Make sure to handle JWT token expiration and refresh in your native app and Laravel API.