ghrenig's avatar

Laravel API to native app

Looking to find examples of using laravel as the backend api and then using iOS/swift android/kotlin to connect to laravel api with JWT techniques or similar. Could use OAuth etc but looking for homegrown solution.

0 likes
2 replies
LaryAI's avatar
Level 58

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:

  1. Install the tymon/jwt-auth package in your Laravel project using Composer:
composer require tymon/jwt-auth
  1. Publish the JWT configuration file:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
  1. Generate a secret key for JWT:
php artisan jwt:secret
  1. 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]);
});
  1. 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.

  2. Include the JWT token in the Authorization header of your API requests from the native app:

Authorization: Bearer <JWT token>
  1. In Laravel, use the jwt.auth middleware 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.

aurawindsurfing's avatar

Hey,

JWT token is nothin else then just a hash stored somewhere that you look for then giving access to the route.

The easiest way to see API work in Laravel is no to return view in your controller. If you do this then it will return pure JSON which is exactly what your native app will look for.

Then you create those routes within api.php and not web.php and authenticate it with the token.

That is it. API is no different then just a view it is just presented in different way.

Good luck!

Please or to participate in this conversation.