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.
Related
I have been using Laravel passport to response Api data, I want to response favorite status by user of product if a user login (token paste in header to validate with passport authentication Middleware). Is there a solution to determine if a user login or not without using Middleware "api" in route Api or separate Api url based user login and non user-login?
I just found out that without middleware we can use Auth::guard('api') to validate the bearer token, so just add authorization header with bearer token and check user in controller using Auth::guard('api')
I'm building an app, with Laravel backend and Vue3. Both apps are on different domains. I'm doing axios API calls from Vue. On Laravel I have Sanctum installed to handle my authorisation, login, etc... I tried a lot of stuff, from storing token to localStorage (not a good practice as it is not secured). So I read more, found out that I have to just send - withCredentials: true and it will handle everything with a cookie, out of the box. It does not work. Then I read that it does not work if they are on different domains. I'm not sure how to handle this anymore.
Is this all true? Is sanctum way to go?If not, what is the best way for secured auth? Will it work on same domains and is there a way to work with different domains?
Does anyone have an idea how to handle this?
Thank you!!!
having 2 domains doesn't change anything. The logic is very simple. basically you have a token (key) and you will communicate with this key. you will send the token to the client when the conditions are met. than after, client say "if this your token, give my credentials."
just use sanctum token:
$user->createToken($request->name)->plainTextToken;
than you return Bearer token if the conditions are met:
Authorization: Bearer <token>
and protect your route with sanctum middleware:
Route::middleware('auth:sanctum')->get('/user', function (Request $request)
finally if the key is correct:
return response($user, 200);
I just trying to makes my auth flow more secure using a cookie on Laravel 5.7
Here my code
/**
* auth logic
*/
return response()->json(["status" => "logged in"], 200)->cookie('token', $token, $lifetime);
Then the cookie will be saved on the browser and will be used on every request.
On header with Axios
"cookie":"token={token}"
And I validate the auth using default middleware
Route::group(['middleware' => ['auth:api']])
But the auth:api did not recognize it, I can make custom middleware by manually detect the cookie, but I can't use the auth()->user() function on it.
Is there any solution for this?
From your sample code I believe your app is built on a stateless architecture where you have your JavaScript client and laravel api.
Now I am a bit confused as to why you do not want the client storing the token, if you just want to escape cross site scripting vulnerability (XSS) then you have to prepare to deal with cross site request forgery (CSRF) if you store the token in the browsers cookie.
Regarding the middleware not being able to find the token, by default the middleware is configured to lookup tokens in the request header (specifically the Authorization header) so if you decide to store it in the cookie, you have to find a way to change the token lookup in the api middleware which unfortunately I have not done before in laravel.
APIs don't generally store and send cookies. Therefore the api token authentication guard will not look for the token in a cookie. There are multiple options you can send it as though the easiest one in axios:
{
headers: {
Authorization: `Bearer ${token}`
}
}
Is it possible to use Laravel Passport with web page authentication? I have a larvel project which is using both API and WEB sides. I am trying to integrate the login and authentication with passport.
The auth/token giving me the Bearer token. But how can I add the authentication middleware in the dashboard redirection after login?
I tried adding access_token key in cookie with the token value. And added
Passport::cookie('access_token');
in AuthServiceProvider.php boot() function. But still I am getting the error
{"status":"error","data":{"message":"Unauthorized"}}
Is it possible to implement my idea? If so please help on this.
I am not sure if I have understood you correctly, but the access token should be placed in the headers not as cookie:
Authorization: Bearer {token}
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');