I'm using Laravel 8 / VueJs / Sanctum. And I found a small issue I'm not sure if its a security issue or not but I'm thinking its an exploit in Sanctum
I'm calling my Vue components in my blade files
And I can send and receive the response to all routes that I have in api.php without sending the token.
Also : All my routes are in sanctum middleware as you can see
all my routes are working fine but the one /user it redirect me to home
is that possible to receive a response without sending a token, after I logged in ?
if Yes why I can receive a response from all my routes but /user it redirect me to /home
Route::middleware(['auth:sanctum'])->group(function () {
Route::get('/user', function(Request $request){
return $request->user();
});
// Chat routes
Route::prefix('/chat')->group(function(){
Route::post('/messages', [App\Http\Controllers\Api\ApiChatController::class, 'store'])->name('api/send-message');
Route::get('/messages', [App\Http\Controllers\Api\ApiChatController::class, 'show'])->name('api/recent-chat');
Route::get('/messages/{user}', [App\Http\Controllers\Api\ApiChatController::class, 'show'])->name('api/open-chat');
Route::get('/threads', [App\Http\Controllers\Api\ApiChatController::class, 'index'])->name('api/all-chat-threads');
});
// dating routes
Route::prefix('/dating')->group(function(){
Route::get('/search', [App\Http\Controllers\DatingController::class, 'search'])->name('api/search');
});
});
Sanctum using token and cookie too for user auth. If you are calling over the browser a page which is guarded by sanctum then laravel use cookie auth. if you make a api calling by javascript then laravel needs the token.
So i think everything is right.
Related
I have been working with Laravel since version 5.X up to version 8.X but always use it for backend API (never used blade template), and always pair it with VueJS on the front-end using JWT authentication (also never messed with any other authentication method).
Now with Laravel 9 and Vue 3, Im trying to use native Laravel Jetstream that uses SANCTUM and Vue+Inertia JS, and I'm quite lost with the authentication process. with JWT method, once the user succesfully login on the browser, all api request to Laravel will be authenticated using Authoraziation header. but this seems a different case with Sanctum.
After deploying and installing Jetstream and completed all the set-up. I created a user and loggedin with that user details. and I notice few things, there is a default API route
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
when I tried to directly access my.domain/api/user I notice it was redirected to GET /login
then redirected again to GET /dashboard
I then created a test api route using below
Route::get('test', function( Request $req) {
dd( [
'test' => $req->all(),
'user' => auth()->user(),
'request' => $req
] );
});
and I notice this request is not authenticated even when the cookies is present on the request as Im when I'm alraedy logged-in on the same browser, the auth()->user() is null.
I tried adding auth:sanctum middleware
Route::middleware('auth:sanctum')->get('test', function( Request $req) {
dd( [
'test' => $req->all(),
'user' => auth()->user(),
'request' => $req
] );
});
but having sanctum middle behave the same as the api/user where if i open api/test directly on the browser, it gets redirected to GET /login then redirected again to GET /dashboard and I'm quite lost at this point. I tried reading the docs and it says I have to do a separate authentication for this that would issue an API token and I was thinking I might better be going back with using JWT auth as it seems a lot easier to deal with.
So my question is; How can I authenticate an API end-point without having to redirect it to /login then /dashboard if the user is already logged in on my application using default sanctum authentication.
My goal is just to simply create /api/test that will be automatically authenticated if user already loggedin on the same browser and return the data I set on its return value and not doing any redirects.
Appreciate any help
I have got the same issue with laravel8
Jetstream and inertia vue3.
Am looking for the solution since 3 days posting messages on discord, searching on YouTube and more but nothing.
When i make an api call from your SPA to laravel, i got UNAUTHENTICATED response.
on postman you need put
headers
Accept = application/json
this tells your application know how works with Json
and go stop redirect to "Login"
I am trying to protect API routes with a bearer token using Laravel Sanctum.
I have added the middleware correctly for the route as follows in api.php. The api/me route is set to return auth()->user();
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('/me', 'App\Http\Controllers\APIController#me');
});
To test this, I first login successfully and generate a bearer token, so that is working fine.
However, when I try to access the api/me route without the bearer token, it still displays the full user. It is not supposed to be allowing access to the route without a bearer token, why is it doing that?
I've searched for hours but no joy - does anyone have any insight?
I'm just guessing here.. Did you "EnsureFrontendRequestAreStateful" in kernel.php?
Because then Sanctum will use Session-Cookie based authentication. Sanctum will only use the bearer token if you authenticate third party apps, that don't run on your domain or subdomain.
If you don't want to use session-cookie based authentication for your SPA remove the "EnsureFrontendRequestsAreStateful" class from kernel.php.
Now Sanctum will always use the bearer token for authentication.
I'm trying to create SPA. I use Laravel API for backend and Nuxt.js for frontend. I want to authenticate users via Laravel Sanctum. I run backend on localhost:8000 and frontend on localhost:3000. SANCTUM_STATEFUL_DOMAINS is set to localhost:3000, SESSION_DOMAIN is set to localhost and SESSION_DRIVER is set to cookie.
I created login and logout in my app and everything works great until I make first request after logging in. I just wanted my app to return all users:
Route::middleware('auth:sanctum')->get('/users', function() { return User::all(); });
but it returns 401 unauthenticated. I don't know why is that happening. The route used for returning logged in user uses the same middleware:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
and works perfectly (Nuxt returns logged in user with every page change). I called users route with axios:
axios.get('http://localhost:8000/api/users')
What can cause this problem? This is very frustrating because I struggled a lot just to get the login and logout working.
I also thought about running API on api.domain.test and frontend on domain.test but is it possible to hook up a domain like that to Nuxt locally?
It returns unauthorized because the call to the endpoint doesn't have access token of the user.
The idea is that when you login auth:sanctum returns access token to the client so that it can use it to access the data in all of it's next calls.
To do that you need to use authentication module in nuxt check this
The problem you are going to face next is that SPA doesn't have middleware so you need to set your app as universal instead of spa to be able to use the middleware in the client side
Im using Laravels default auth to lock down some paths in the routes/api.php file.
Route::get('/projects', 'ProjectController#index')->middleware('auth:api');
I log the user in via a PHP form (not via a http request via Vue).
This creates the session and when I submit a HTTP request via Vue I can see that the header includes the Cookie and X-CSRF-Token however I keep getting a 401 {"error":"Unauthenticated."}
In my config/auth I have api driver set as 'token' (have tried changing this to 'session' but that did work :/)
From my understanding and what I have read online I should be able to use the default Laravel auth functionality to accomplish API calls from Vue HTTP requests.
this.$http.get('/api/projects')
.then(response => {
this.projects = response.body;
})
.catch (err => {
console.log(err);
});
I've read about methods of authenticating by generating an JWT token and storing that in local storage when the user logs in. Is this the method I should use or should I be able to accomplish it with the default Laravel Auth middleware?
Hope my questions make sense, any help/advice would be appreciated.
The auth:api middleware doesn't use cookies, it uses api_token param, which can be passed via get or Bearer <token> header. Just use web middleware.
I suppose you need to access the same route in two ways - for API users and for browser users. So why don't you create two routes for one action?
// api group with /api prefix
Route::get('/projects', 'ProjectController#index')->middleware('auth:api');
// web group
Route::get('/projects', 'ProjectController#index')->middleware('web');
For my API i'm using this package tymondesigns/jwt-auth with Laravel.
Security is very important! Tokens will be blacklisted after every request with a new token in the response. While doing some tests using both middlewares jwt.auth and jwt.refresh on the same route I get mixed results. Sometimes it works OK, sometimes I get a 401 unauthorized and have to login again.
I'm using the jtw.auth middleware so I can make use of Auth::user() in my app.
$api->group(['middleware' => ['jwt.auth', 'jwt.refresh']], function ($api)
{
// Protected routes here
});
Does someone have a working example for this?