I'm trying to make a transition from my project being a monolith to having a separate frontend and backend. In the original authentication implementation I used laravel/breeze. For this API I want to use Jsonwebtoken. However, I have problems as below.
I tried to make an API response on the controller but the response I received was instead a login page when testing in Postman. Here are some snippets of my code:
AuthController.php:
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
public function userProfile()
{
try {
if (!Auth::check()) {
return ApiResponses::unauthorized("Unauthorized");
}
$user = Auth::user()->toArray();
return ApiResponses::ok($user, "Success to login");
} catch (Exception $e) {
return ApiResponses::serverError("An error occured: " . $e->getMessage());
}
}
ApiResponses.php
public function toResponse($request): JsonResponse
{
$response = [
'success' => $this->httpCode >= 200 && $this->httpCode < 300,
];
if (!$response['success']) {
$response['errorMessage'] = $this->errorMessage;
Log::error('API Error: ' . $this->errorMessage);
} else {
$response['message'] = $this->message ?: '';
$response['data'] = $this->data;
}
return response()->json($response, $this->httpCode, [], JSON_UNESCAPED_UNICODE);
}
public static function unauthorized(string $errorMessage = "Unauthorized")
{
return new static(401, [], $errorMessage);
}
public static function ok(array $data, string $message = '')
{
return new static(200, $data, '', $message);
}
api.php
Route::controller(AuthController::class)->prefix('v1')->group(function () {
Route::post('auth/login', 'login');
Route::post('auth/register', 'register');
Route::get('auth/profile', 'userProfile');
Route::post('auth/logout', 'logout');
});