1

I am currently learning Laravel and using Sanctum to perform authentication.

I have a route working /register and /login and I am trying to create /me endpoint that's protected using auth:sanctum which as a test just returns the authenticated user.

In my api.php I have the following:

Route::post('/auth/register', [UserController::class, "register"]);

Route::post('/auth/login', [UserController::class, "login"]);

Route::middleware('auth:sanctum')->get('/me', function(){
    return auth()->user();
});

In my UserController class I have the following:

class UserController extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function register(Request $request)
    {
        $user = User::create([
            'name' => $request['name'],
            'email' => $request['email'],
            'password' => bcrypt($request['password'])
        ]);

        return response([
            'success' => $user->createToken('API Token')->plainTextToken
        ]);
    }

    public function login(Request $request)
    {
        $attr = $request->validate([
            'email' => 'required|string|email|',
            'password' => 'required|string|min:6'
        ]);

        if (!Auth::attempt($attr))
        {
            return response('Credentials not found', 401);
        }

        return response([
            'token' => auth()->user()->createToken('API Token')->plainTextToken
        ]);
    }

    public function logout()
    {
        auth()->user()->tokens()->delete();

        return [
            'message' => 'Tokens Revoked'
        ];
    }
}

The /login and /register routes work fine, however, when I attempt to use the /logout or /me route which is using auth:sanctum middleware, I get the following error:

Symfony\Component\Routing\Exception\RouteNotFoundException
Route [login] not defined.

Everything I've Google'd seem to show that I've implemented it correctly, so I'm not sure what I'm missing.

Boardy
  • 35,417
  • 104
  • 256
  • 447
  • 1
    Set name for login route `Route::post('/auth/login', [UserController::class, "login"])->name('login');` – Lessmore Jun 12 '21 at 21:40
  • What is the URL you are trying to use ? If you have your routes in `api.php`, you have to use `/api/ROUTE`, are you using `/api/me` ? – matiaslauriti Jun 12 '21 at 21:40
  • @Lessmore When I tried that I then get, the GET method is not supported for this route (using /api/me) supported methods post. – Boardy Jun 12 '21 at 21:45
  • @matiaslauriti Yes my path is /api/me, technically its actually /backend/api/me but in the .htaccess file I have RewriteBase /backend (this is aliased in my Apache config as the plan will be for a React JS app so its aliased to /backend. So my paths are /backend/api/auth/login, /backend/api/auth/register /backend/api/me – Boardy Jun 12 '21 at 21:47
  • @Lessmore I am using application/json but the /me has no body, so don't believe setting the Content-Type would be valid, but tried it anyway, but it doesn't seem to have made a difference – Boardy Jun 12 '21 at 21:52
  • `/me` has not body beacuse user not logged in, because provided credential is not valid, then app try redirect request to `login`, by setting `content-type` tell to laravel return error message instead of redirect to `login` – Lessmore Jun 12 '21 at 21:56
  • @Lessmore, when I said /me has no body, I meant, I'm not sending any data in the request, its just a GET route to return the authenticated user object. Although you did point me in the right direction about not being authenticated as I forgot to provide the Authorization bearer token header, so I've added that now but now get a different exception saying "unknown column 'api_token' in where clause. I've reran php artisan migrate and it comes up saying nothing to migrate – Boardy Jun 12 '21 at 22:07
  • maybe this help you : https://stackoverflow.com/a/63302055/1804223 – Lessmore Jun 12 '21 at 22:40
  • 1
    also about headers, you must set `Accept: application/json` in your request – Lessmore Jun 12 '21 at 22:41
  • @Lessmore I spotted that SO post as well, and I tried changing the driver to sanctum in the config/auth.php but when I do that and send the request, it just completely fails with the error: 'Error: Server returned nothing (no headers, no data)'. If I hadn't know laravel was so popular I'd have prob deemed it to be unreliable and overly complicated as following their own user guides doesn't seem to work :( – Boardy Jun 12 '21 at 22:52
  • looks for errors in `storage/logs/laravel.log` – Lessmore Jun 12 '21 at 23:14
  • Nothing appears to get logged out, nothing in the apache error log either – Boardy Jun 13 '21 at 10:24
  • Actually I think the apache error log is having a segmentation fault – Boardy Jun 13 '21 at 10:35
  • Ah managed to fix it I think. I changed auth.php so that the api driver was session (it was defaulted to token) and now it appears to be working correctly – Boardy Jun 13 '21 at 13:13

1 Answers1

0

I managed to figure out the problem with some help from @LessMore.

I think most of the problem the auth.php being wrong. Under config/auth.php, under the api section change the driver from token to session, so it should be as follows:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'session',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

The other thing was I was forgetting to add the Authorization header with the bearer token that is returned on the login and to put Accept application/json header.

Boardy
  • 35,417
  • 104
  • 256
  • 447